blob: 56a3f4b14a4c66455cf33c040e8e70f952fd7966 [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:
227
228//usage:#define hush_trivial_usage NOUSAGE_STR
229//usage:#define hush_full_usage ""
230//usage:#define lash_trivial_usage NOUSAGE_STR
231//usage:#define lash_full_usage ""
232//usage:#define msh_trivial_usage NOUSAGE_STR
233//usage:#define msh_full_usage ""
234
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000235
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200236/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000237#define LEAK_HUNTING 0
238#define BUILD_AS_NOMMU 0
239/* Enable/disable sanity checks. Ok to enable in production,
240 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
241 * Keeping 1 for now even in released versions.
242 */
243#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200244/* Slightly bigger (+200 bytes), but faster hush.
245 * So far it only enables a trick with counting SIGCHLDs and forks,
246 * which allows us to do fewer waitpid's.
247 * (we can detect a case where neither forks were done nor SIGCHLDs happened
248 * and therefore waitpid will return the same result as last time)
249 */
250#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200251/* TODO: implement simplified code for users which do not need ${var%...} ops
252 * So far ${var%...} ops are always enabled:
253 */
254#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000255
256
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000257#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000258# undef BB_MMU
259# undef USE_FOR_NOMMU
260# undef USE_FOR_MMU
261# define BB_MMU 0
262# define USE_FOR_NOMMU(...) __VA_ARGS__
263# define USE_FOR_MMU(...)
264#endif
265
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200266#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100267#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000268/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000269# undef CONFIG_FEATURE_SH_STANDALONE
270# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000271# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100272# undef IF_NOT_FEATURE_SH_STANDALONE
273# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000274# define IF_FEATURE_SH_STANDALONE(...)
275# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000276#endif
277
Denis Vlasenko05743d72008-02-10 12:10:08 +0000278#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000279# undef ENABLE_FEATURE_EDITING
280# define ENABLE_FEATURE_EDITING 0
281# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
282# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000283#endif
284
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000285/* Do we support ANY keywords? */
286#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000287# define HAS_KEYWORDS 1
288# define IF_HAS_KEYWORDS(...) __VA_ARGS__
289# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000290#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000291# define HAS_KEYWORDS 0
292# define IF_HAS_KEYWORDS(...)
293# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000294#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000295
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000296/* If you comment out one of these below, it will be #defined later
297 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000298#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000299/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000300#define debug_printf_parse(...) do {} while (0)
301#define debug_print_tree(a, b) do {} while (0)
302#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000303#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000304#define debug_printf_jobs(...) do {} while (0)
305#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200306#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000307#define debug_printf_glob(...) do {} while (0)
308#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000309#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000310#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000311
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000312#define ERR_PTR ((void*)(long)1)
313
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200314#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000315
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200316#define _SPECIAL_VARS_STR "_*@$!?#"
317#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
318#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
319
320#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000321
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200322struct variable;
323
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000324static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
325
326/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000327 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000328 */
329#if !BB_MMU
330typedef struct nommu_save_t {
331 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200332 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000333 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000334 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000335} nommu_save_t;
336#endif
337
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000338typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000339 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000340#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000341 RES_IF ,
342 RES_THEN ,
343 RES_ELIF ,
344 RES_ELSE ,
345 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000346#endif
347#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000348 RES_FOR ,
349 RES_WHILE ,
350 RES_UNTIL ,
351 RES_DO ,
352 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000353#endif
354#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000355 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000356#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000357#if ENABLE_HUSH_CASE
358 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200359 /* three pseudo-keywords support contrived "case" syntax: */
360 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
361 RES_MATCH , /* "word)" */
362 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000363 RES_ESAC ,
364#endif
365 RES_XXXX ,
366 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000367} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000368
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000369typedef struct o_string {
370 char *data;
371 int length; /* position where data is appended */
372 int maxlen;
373 /* Protect newly added chars against globbing
374 * (by prepending \ to *, ?, [, \) */
375 smallint o_escape;
376 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000377 /* At least some part of the string was inside '' or "",
378 * possibly empty one: word"", wo''rd etc. */
379 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000380 smallint has_empty_slot;
381 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
382} o_string;
383enum {
384 MAYBE_ASSIGNMENT = 0,
385 DEFINITELY_ASSIGNMENT = 1,
386 NOT_ASSIGNMENT = 2,
387 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
388};
389/* Used for initialization: o_string foo = NULL_O_STRING; */
390#define NULL_O_STRING { NULL }
391
392/* I can almost use ordinary FILE*. Is open_memstream() universally
393 * available? Where is it documented? */
394typedef struct in_str {
395 const char *p;
396 /* eof_flag=1: last char in ->p is really an EOF */
397 char eof_flag; /* meaningless if ->p == NULL */
398 char peek_buf[2];
399#if ENABLE_HUSH_INTERACTIVE
400 smallint promptme;
401 smallint promptmode; /* 0: PS1, 1: PS2 */
402#endif
403 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200404 int (*get) (struct in_str *) FAST_FUNC;
405 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000406} in_str;
407#define i_getch(input) ((input)->get(input))
408#define i_peek(input) ((input)->peek(input))
409
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200410/* The descrip member of this structure is only used to make
411 * debugging output pretty */
412static const struct {
413 int mode;
414 signed char default_fd;
415 char descrip[3];
416} redir_table[] = {
417 { O_RDONLY, 0, "<" },
418 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
419 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
420 { O_CREAT|O_RDWR, 1, "<>" },
421 { O_RDONLY, 0, "<<" },
422/* Should not be needed. Bogus default_fd helps in debugging */
423/* { O_RDONLY, 77, "<<" }, */
424};
425
Eric Andersen25f27032001-04-26 23:22:31 +0000426struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000427 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000428 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000429 int rd_fd; /* fd to redirect */
430 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
431 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000432 smallint rd_type; /* (enum redir_type) */
433 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000434 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200435 * bit 0: do we need to trim leading tabs?
436 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000437 */
Eric Andersen25f27032001-04-26 23:22:31 +0000438};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000439typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200440 REDIRECT_INPUT = 0,
441 REDIRECT_OVERWRITE = 1,
442 REDIRECT_APPEND = 2,
443 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000444 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200445 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000446
447 REDIRFD_CLOSE = -3,
448 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000449 REDIRFD_TO_FILE = -1,
450 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000451
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000452 HEREDOC_SKIPTABS = 1,
453 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000454} redir_type;
455
Eric Andersen25f27032001-04-26 23:22:31 +0000456
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000457struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000458 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000459 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000460 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200461 smallint cmd_type; /* CMD_xxx */
462#define CMD_NORMAL 0
463#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200464
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200465/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200466#if ENABLE_HUSH_BASH_COMPAT
467# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000468#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200469
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200470/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200471//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200472// It is hard to implement correctly, it adds significant amounts of tricky code,
473// and all this is only useful for really obscure export statements
474// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
475// guards the code which implements it, but I have doubts it works
476// in all cases (especially with mixed globbed/non-globbed arguments)
477
478#if ENABLE_HUSH_FUNCTIONS
479# define CMD_FUNCDEF 3
480#endif
481
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200482 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
483 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000484#if !BB_MMU
485 char *group_as_string;
486#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000487#if ENABLE_HUSH_FUNCTIONS
488 struct function *child_func;
489/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200490 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000491 * When we execute "f1() {a;}" cmd, we create new function and clear
492 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200493 * When we execute "f1() {b;}", we notice that f1 exists,
494 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000495 * we put those fields back into cmd->xxx
496 * (struct function has ->parent_cmd ptr to facilitate that).
497 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
498 * Without this trick, loop would execute a;b;b;b;...
499 * instead of correct sequence a;b;a;b;...
500 * When command is freed, it severs the link
501 * (sets ->child_func->parent_cmd to NULL).
502 */
503#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000504 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000505/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
506 * and on execution these are substituted with their values.
507 * Substitution can make _several_ words out of one argv[n]!
508 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000509 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000510 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000511 struct redir_struct *redirects; /* I/O redirections */
512};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000513/* Is there anything in this command at all? */
514#define IS_NULL_CMD(cmd) \
515 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
516
Eric Andersen25f27032001-04-26 23:22:31 +0000517
518struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000519 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000520 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000521 int alive_cmds; /* number of commands running (not exited) */
522 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000523#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000524 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000525 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000526 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000527#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000528 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000529 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000530 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
531 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000532};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000533typedef enum pipe_style {
534 PIPE_SEQ = 1,
535 PIPE_AND = 2,
536 PIPE_OR = 3,
537 PIPE_BG = 4,
538} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000539/* Is there anything in this pipe at all? */
540#define IS_NULL_PIPE(pi) \
541 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000542
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000543/* This holds pointers to the various results of parsing */
544struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000545 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000546 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000547 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000548 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000549 /* last command in pipe (being constructed right now) */
550 struct command *command;
551 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000552 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000553#if !BB_MMU
554 o_string as_string;
555#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000556#if HAS_KEYWORDS
557 smallint ctx_res_w;
558 smallint ctx_inverted; /* "! cmd | cmd" */
559#if ENABLE_HUSH_CASE
560 smallint ctx_dsemicolon; /* ";;" seen */
561#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000562 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
563 int old_flag;
564 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000565 * example: "if pipe1; pipe2; then pipe3; fi"
566 * when we see "if" or "then", we malloc and copy current context,
567 * and make ->stack point to it. then we parse pipeN.
568 * when closing "then" / fi" / whatever is found,
569 * we move list_head into ->stack->command->group,
570 * copy ->stack into current context, and delete ->stack.
571 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000572 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000573 struct parse_context *stack;
574#endif
575};
576
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000577/* On program start, environ points to initial environment.
578 * putenv adds new pointers into it, unsetenv removes them.
579 * Neither of these (de)allocates the strings.
580 * setenv allocates new strings in malloc space and does putenv,
581 * and thus setenv is unusable (leaky) for shell's purposes */
582#define setenv(...) setenv_is_leaky_dont_use()
583struct variable {
584 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000585 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200586#if ENABLE_HUSH_LOCAL
587 unsigned func_nest_level;
588#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000589 int max_len; /* if > 0, name is part of initial env; else name is malloced */
590 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000591 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000592};
593
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000594enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000595 BC_BREAK = 1,
596 BC_CONTINUE = 2,
597};
598
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000599#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000600struct function {
601 struct function *next;
602 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000603 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000604 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200605# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000606 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200607# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000608};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000609#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000610
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000611
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000612/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000613/* Sorted roughly by size (smaller offsets == smaller code) */
614struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000615 /* interactive_fd != 0 means we are an interactive shell.
616 * If we are, then saved_tty_pgrp can also be != 0, meaning
617 * that controlling tty is available. With saved_tty_pgrp == 0,
618 * job control still works, but terminal signals
619 * (^C, ^Z, ^Y, ^\) won't work at all, and background
620 * process groups can only be created with "cmd &".
621 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
622 * to give tty to the foreground process group,
623 * and will take it back when the group is stopped (^Z)
624 * or killed (^C).
625 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000626#if ENABLE_HUSH_INTERACTIVE
627 /* 'interactive_fd' is a fd# open to ctty, if we have one
628 * _AND_ if we decided to act interactively */
629 int interactive_fd;
630 const char *PS1;
631 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000632# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000633#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000634# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000635#endif
636#if ENABLE_FEATURE_EDITING
637 line_input_t *line_input_state;
638#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000639 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200640 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000641 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200642#if ENABLE_HUSH_RANDOM_SUPPORT
643 random_t random_gen;
644#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000645#if ENABLE_HUSH_JOB
646 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000647 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000648 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000649 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400650# define G_saved_tty_pgrp (G.saved_tty_pgrp)
651#else
652# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000653#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000654 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000655#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000656 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000657#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000658#if ENABLE_HUSH_FUNCTIONS
659 /* 0: outside of a function (or sourced file)
660 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000661 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000662 */
663 smallint flag_return_in_progress;
664#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200665 smallint n_mode;
666#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200667 smallint x_mode;
Denys Vlasenko29082232010-07-16 13:52:32 +0200668# define G_x_mode (G.x_mode)
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200669#else
670# define G_x_mode 0
671#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000672 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000673 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000674 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000675 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000676 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100677 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000678 /* how many non-NULL argv's we have. NB: $# + 1 */
679 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000680 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000681#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000682 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000683#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000684#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000685 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000686 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000687#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000688 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000689 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000690 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000691 struct variable shell_ver;
Denys Vlasenko29082232010-07-16 13:52:32 +0200692 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000693#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000694 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200695# if ENABLE_HUSH_LOCAL
696 struct variable **shadowed_vars_pp;
697 unsigned func_nest_level;
698# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000699#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000700 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200701#if ENABLE_HUSH_FAST
702 unsigned count_SIGCHLD;
703 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200704 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200705#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000706 /* which signals have non-DFL handler (even with no traps set)? */
707 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000708 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000709 sigset_t blocked_set;
710 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000711#if HUSH_DEBUG
712 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000713 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000714#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200715 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000716};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000717#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000718/* Not #defining name to G.name - this quickly gets unwieldy
719 * (too many defines). Also, I actually prefer to see when a variable
720 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000721#define INIT_G() do { \
722 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
723} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000724
725
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000726/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200727static int builtin_cd(char **argv) FAST_FUNC;
728static int builtin_echo(char **argv) FAST_FUNC;
729static int builtin_eval(char **argv) FAST_FUNC;
730static int builtin_exec(char **argv) FAST_FUNC;
731static int builtin_exit(char **argv) FAST_FUNC;
732static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000733#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200734static int builtin_fg_bg(char **argv) FAST_FUNC;
735static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000736#endif
737#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200738static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000739#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200740#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200741static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200742#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000743#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200744static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000745#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400746#if ENABLE_PRINTF
747static int builtin_printf(char **argv) FAST_FUNC;
748#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200749static int builtin_pwd(char **argv) FAST_FUNC;
750static int builtin_read(char **argv) FAST_FUNC;
751static int builtin_set(char **argv) FAST_FUNC;
752static int builtin_shift(char **argv) FAST_FUNC;
753static int builtin_source(char **argv) FAST_FUNC;
754static int builtin_test(char **argv) FAST_FUNC;
755static int builtin_trap(char **argv) FAST_FUNC;
756static int builtin_type(char **argv) FAST_FUNC;
757static int builtin_true(char **argv) FAST_FUNC;
758static int builtin_umask(char **argv) FAST_FUNC;
759static int builtin_unset(char **argv) FAST_FUNC;
760static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000761#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200762static int builtin_break(char **argv) FAST_FUNC;
763static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000764#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000765#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200766static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000767#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000768
769/* Table of built-in functions. They can be forked or not, depending on
770 * context: within pipes, they fork. As simple commands, they do not.
771 * When used in non-forking context, they can change global variables
772 * in the parent shell process. If forked, of course they cannot.
773 * For example, 'unset foo | whatever' will parse and run, but foo will
774 * still be set at the end. */
775struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100776 const char *b_cmd;
777 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000778#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100779 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200780# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000781#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200782# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000783#endif
784};
785
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200786static const struct built_in_command bltins1[] = {
787 BLTIN("." , builtin_source , "Run commands in a file"),
788 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000789#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200790 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000791#endif
792#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200793 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000794#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200795 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000796#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200797 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000798#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200799 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
800 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
801 BLTIN("exit" , builtin_exit , "Exit"),
802 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000803#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200804 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000805#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000806#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200807 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000808#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000809#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200810 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000811#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200812#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200813 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200814#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000815#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200816 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000817#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200818 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000819#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200820 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000821#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200822 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
823 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200824#if ENABLE_HUSH_BASH_COMPAT
825 BLTIN("source" , builtin_source , "Run commands in a file"),
826#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200827 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100828 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100829 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200830 BLTIN("umask" , builtin_umask , "Set file creation mask"),
831 BLTIN("unset" , builtin_unset , "Unset variables"),
832 BLTIN("wait" , builtin_wait , "Wait for process"),
833};
834/* For now, echo and test are unconditionally enabled.
835 * Maybe make it configurable? */
836static const struct built_in_command bltins2[] = {
837 BLTIN("[" , builtin_test , NULL),
838 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400839#if ENABLE_PRINTF
840 BLTIN("printf" , builtin_printf , NULL),
841#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200842 BLTIN("pwd" , builtin_pwd , NULL),
843 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000844};
845
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000846
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000847/* Debug printouts.
848 */
849#if HUSH_DEBUG
850/* prevent disasters with G.debug_indent < 0 */
851# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
852# define debug_enter() (G.debug_indent++)
853# define debug_leave() (G.debug_indent--)
854#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200855# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000856# define debug_enter() ((void)0)
857# define debug_leave() ((void)0)
858#endif
859
860#ifndef debug_printf
861# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
862#endif
863
864#ifndef debug_printf_parse
865# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
866#endif
867
868#ifndef debug_printf_exec
869#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
870#endif
871
872#ifndef debug_printf_env
873# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
874#endif
875
876#ifndef debug_printf_jobs
877# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
878# define DEBUG_JOBS 1
879#else
880# define DEBUG_JOBS 0
881#endif
882
883#ifndef debug_printf_expand
884# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
885# define DEBUG_EXPAND 1
886#else
887# define DEBUG_EXPAND 0
888#endif
889
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200890#ifndef debug_printf_varexp
891# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
892#endif
893
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000894#ifndef debug_printf_glob
895# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
896# define DEBUG_GLOB 1
897#else
898# define DEBUG_GLOB 0
899#endif
900
901#ifndef debug_printf_list
902# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
903#endif
904
905#ifndef debug_printf_subst
906# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
907#endif
908
909#ifndef debug_printf_clean
910# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
911# define DEBUG_CLEAN 1
912#else
913# define DEBUG_CLEAN 0
914#endif
915
916#if DEBUG_EXPAND
917static void debug_print_strings(const char *prefix, char **vv)
918{
919 indent();
920 fprintf(stderr, "%s:\n", prefix);
921 while (*vv)
922 fprintf(stderr, " '%s'\n", *vv++);
923}
924#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200925# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000926#endif
927
928
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000929/* Leak hunting. Use hush_leaktool.sh for post-processing.
930 */
931#if LEAK_HUNTING
932static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000933{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000934 void *ptr = xmalloc((size + 0xff) & ~0xff);
935 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
936 return ptr;
937}
938static void *xxrealloc(int lineno, void *ptr, size_t size)
939{
940 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
941 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
942 return ptr;
943}
944static char *xxstrdup(int lineno, const char *str)
945{
946 char *ptr = xstrdup(str);
947 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
948 return ptr;
949}
950static void xxfree(void *ptr)
951{
952 fdprintf(2, "free %p\n", ptr);
953 free(ptr);
954}
Denys Vlasenko8391c482010-05-22 17:50:43 +0200955# define xmalloc(s) xxmalloc(__LINE__, s)
956# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
957# define xstrdup(s) xxstrdup(__LINE__, s)
958# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000959#endif
960
961
962/* Syntax and runtime errors. They always abort scripts.
963 * In interactive use they usually discard unparsed and/or unexecuted commands
964 * and return to the prompt.
965 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
966 */
967#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200968# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000969# define syntax_error(lineno, msg) syntax_error(msg)
970# define syntax_error_at(lineno, msg) syntax_error_at(msg)
971# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
972# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
973# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000974#endif
975
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000976static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000977{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000978 va_list p;
979
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000980#if HUSH_DEBUG >= 2
981 bb_error_msg("hush.c:%u", lineno);
982#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000983 va_start(p, fmt);
984 bb_verror_msg(fmt, p, NULL);
985 va_end(p);
986 if (!G_interactive_fd)
987 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000988}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000989
990static void syntax_error(unsigned lineno, const char *msg)
991{
992 if (msg)
993 die_if_script(lineno, "syntax error: %s", msg);
994 else
995 die_if_script(lineno, "syntax error", NULL);
996}
997
998static void syntax_error_at(unsigned lineno, const char *msg)
999{
1000 die_if_script(lineno, "syntax error at '%s'", msg);
1001}
1002
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001003static void syntax_error_unterm_str(unsigned lineno, const char *s)
1004{
1005 die_if_script(lineno, "syntax error: unterminated %s", s);
1006}
1007
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001008/* It so happens that all such cases are totally fatal
1009 * even if shell is interactive: EOF while looking for closing
1010 * delimiter. There is nowhere to read stuff from after that,
1011 * it's EOF! The only choice is to terminate.
1012 */
1013static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001014static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001015{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001016 char msg[2] = { ch, '\0' };
1017 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001018 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001019}
1020
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001021static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001022{
1023 char msg[2];
1024 msg[0] = ch;
1025 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001026 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001027}
1028
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001029#if HUSH_DEBUG < 2
1030# undef die_if_script
1031# undef syntax_error
1032# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001033# undef syntax_error_unterm_ch
1034# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001035# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001036#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001037# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001038# define syntax_error(msg) syntax_error(__LINE__, msg)
1039# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1040# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1041# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1042# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001043#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001044
Denis Vlasenko552433b2009-04-04 19:29:21 +00001045
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001046#if ENABLE_HUSH_INTERACTIVE
1047static void cmdedit_update_prompt(void);
1048#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001049# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001050#endif
1051
1052
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001053/* Utility functions
1054 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001055/* Replace each \x with x in place, return ptr past NUL. */
1056static char *unbackslash(char *src)
1057{
Denys Vlasenko71885402009-09-24 01:44:13 +02001058 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001059 while (1) {
1060 if (*src == '\\')
1061 src++;
1062 if ((*dst++ = *src++) == '\0')
1063 break;
1064 }
1065 return dst;
1066}
1067
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001068static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001069{
1070 int i;
1071 unsigned count1;
1072 unsigned count2;
1073 char **v;
1074
1075 v = strings;
1076 count1 = 0;
1077 if (v) {
1078 while (*v) {
1079 count1++;
1080 v++;
1081 }
1082 }
1083 count2 = 0;
1084 v = add;
1085 while (*v) {
1086 count2++;
1087 v++;
1088 }
1089 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1090 v[count1 + count2] = NULL;
1091 i = count2;
1092 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001093 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001094 return v;
1095}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001096#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001097static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1098{
1099 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1100 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1101 return ptr;
1102}
1103#define add_strings_to_strings(strings, add, need_to_dup) \
1104 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1105#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001106
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001107/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001108static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001109{
1110 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001111 v[0] = add;
1112 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001113 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001114}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001115#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001116static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1117{
1118 char **ptr = add_string_to_strings(strings, add);
1119 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1120 return ptr;
1121}
1122#define add_string_to_strings(strings, add) \
1123 xx_add_string_to_strings(__LINE__, strings, add)
1124#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001125
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001126static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001127{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001128 char **v;
1129
1130 if (!strings)
1131 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001132 v = strings;
1133 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001134 free(*v);
1135 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001136 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001137 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001138}
1139
Denis Vlasenko76d50412008-06-10 16:19:39 +00001140
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001141/* Helpers for setting new $n and restoring them back
1142 */
1143typedef struct save_arg_t {
1144 char *sv_argv0;
1145 char **sv_g_argv;
1146 int sv_g_argc;
1147 smallint sv_g_malloced;
1148} save_arg_t;
1149
1150static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1151{
1152 int n;
1153
1154 sv->sv_argv0 = argv[0];
1155 sv->sv_g_argv = G.global_argv;
1156 sv->sv_g_argc = G.global_argc;
1157 sv->sv_g_malloced = G.global_args_malloced;
1158
1159 argv[0] = G.global_argv[0]; /* retain $0 */
1160 G.global_argv = argv;
1161 G.global_args_malloced = 0;
1162
1163 n = 1;
1164 while (*++argv)
1165 n++;
1166 G.global_argc = n;
1167}
1168
1169static void restore_G_args(save_arg_t *sv, char **argv)
1170{
1171 char **pp;
1172
1173 if (G.global_args_malloced) {
1174 /* someone ran "set -- arg1 arg2 ...", undo */
1175 pp = G.global_argv;
1176 while (*++pp) /* note: does not free $0 */
1177 free(*pp);
1178 free(G.global_argv);
1179 }
1180 argv[0] = sv->sv_argv0;
1181 G.global_argv = sv->sv_g_argv;
1182 G.global_argc = sv->sv_g_argc;
1183 G.global_args_malloced = sv->sv_g_malloced;
1184}
1185
1186
Denis Vlasenkod5762932009-03-31 11:22:57 +00001187/* Basic theory of signal handling in shell
1188 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001189 * This does not describe what hush does, rather, it is current understanding
1190 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001191 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1192 *
1193 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1194 * is finished or backgrounded. It is the same in interactive and
1195 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001196 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001197 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001198 * backgrounds (i.e. stops) or kills all members of currently running
1199 * pipe.
1200 *
1201 * Wait builtin in interruptible by signals for which user trap is set
1202 * or by SIGINT in interactive shell.
1203 *
1204 * Trap handlers will execute even within trap handlers. (right?)
1205 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001206 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1207 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001208 *
1209 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001210 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001211 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001212 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001213 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001214 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001215 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001216 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001217 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001218 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001219 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001220 *
1221 * SIGQUIT: ignore
1222 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001223 * SIGHUP (interactive):
1224 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001225 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001226 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1227 * that all pipe members are stopped. Try this in bash:
1228 * while :; do :; done - ^Z does not background it
1229 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001230 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001231 * of the command line, show prompt. NB: ^C does not send SIGINT
1232 * to interactive shell while shell is waiting for a pipe,
1233 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001234 * Example 1: this waits 5 sec, but does not execute ls:
1235 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1236 * Example 2: this does not wait and does not execute ls:
1237 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1238 * Example 3: this does not wait 5 sec, but executes ls:
1239 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001240 *
1241 * (What happens to signals which are IGN on shell start?)
1242 * (What happens with signal mask on shell start?)
1243 *
1244 * Implementation in hush
1245 * ======================
1246 * We use in-kernel pending signal mask to determine which signals were sent.
1247 * We block all signals which we don't want to take action immediately,
1248 * i.e. we block all signals which need to have special handling as described
1249 * above, and all signals which have traps set.
1250 * After each pipe execution, we extract any pending signals via sigtimedwait()
1251 * and act on them.
1252 *
1253 * unsigned non_DFL_mask: a mask of such "special" signals
1254 * sigset_t blocked_set: current blocked signal set
1255 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001256 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001257 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001258 * "trap 'cmd' SIGxxx":
1259 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001260 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001261 * unblock signals with special interactive handling
1262 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001263 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001264 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001265 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001266 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001267 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001268 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001269 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001270 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001271 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001272 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001273 * Standard says "When a subshell is entered, traps that are not being ignored
1274 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001275 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001276 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001277enum {
1278 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001279 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001280 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001281 | (1 << SIGHUP)
1282 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001283 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001284#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001285 | (1 << SIGTTIN)
1286 | (1 << SIGTTOU)
1287 | (1 << SIGTSTP)
1288#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001289};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001290
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001291#if ENABLE_HUSH_FAST
1292static void SIGCHLD_handler(int sig UNUSED_PARAM)
1293{
1294 G.count_SIGCHLD++;
1295//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1296}
1297#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001298
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001299#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001300
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001301/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001302# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001303/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001304# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001305
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001306/* Restores tty foreground process group, and exits.
1307 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001308 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001309 * or called directly with -EXITCODE.
1310 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001311static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001312static void sigexit(int sig)
1313{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001314 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001315 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001316
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001317 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001318 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001319 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1320 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001321
1322 /* Not a signal, just exit */
1323 if (sig <= 0)
1324 _exit(- sig);
1325
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001326 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001327}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001328#else
1329
Denys Vlasenko8391c482010-05-22 17:50:43 +02001330# define disable_restore_tty_pgrp_on_exit() ((void)0)
1331# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001332
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001333#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001334
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001335/* Restores tty foreground process group, and exits. */
1336static void hush_exit(int exitcode) NORETURN;
1337static void hush_exit(int exitcode)
1338{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001339 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1340 /* Prevent recursion:
1341 * trap "echo Hi; exit" EXIT; exit
1342 */
1343 char *argv[] = { NULL, G.traps[0], NULL };
1344 G.traps[0] = NULL;
1345 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001346 builtin_eval(argv);
1347 free(argv[1]);
1348 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001349
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001350#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001351 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001352 sigexit(- (exitcode & 0xff));
1353#else
1354 exit(exitcode);
1355#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001356}
1357
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001358static int check_and_run_traps(int sig)
1359{
Dan Fandrichfdd7b562010-06-18 22:37:42 -07001360 static const struct timespec zero_timespec;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001361 smalluint save_rcode;
1362 int last_sig = 0;
1363
1364 if (sig)
1365 goto jump_in;
1366 while (1) {
1367 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1368 if (sig <= 0)
1369 break;
1370 jump_in:
1371 last_sig = sig;
1372 if (G.traps && G.traps[sig]) {
1373 if (G.traps[sig][0]) {
1374 /* We have user-defined handler */
1375 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1376 save_rcode = G.last_exitcode;
1377 builtin_eval(argv);
1378 free(argv[1]);
1379 G.last_exitcode = save_rcode;
1380 } /* else: "" trap, ignoring signal */
1381 continue;
1382 }
1383 /* not a trap: special action */
1384 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001385#if ENABLE_HUSH_FAST
1386 case SIGCHLD:
1387 G.count_SIGCHLD++;
1388//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1389 break;
1390#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001391 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001392 /* Builtin was ^C'ed, make it look prettier: */
1393 bb_putchar('\n');
1394 G.flag_SIGINT = 1;
1395 break;
1396#if ENABLE_HUSH_JOB
1397 case SIGHUP: {
1398 struct pipe *job;
1399 /* bash is observed to signal whole process groups,
1400 * not individual processes */
1401 for (job = G.job_list; job; job = job->next) {
1402 if (job->pgrp <= 0)
1403 continue;
1404 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1405 if (kill(- job->pgrp, SIGHUP) == 0)
1406 kill(- job->pgrp, SIGCONT);
1407 }
1408 sigexit(SIGHUP);
1409 }
1410#endif
1411 default: /* ignored: */
1412 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1413 break;
1414 }
1415 }
1416 return last_sig;
1417}
1418
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001419
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001420static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001421{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001422 if (force || G.cwd == NULL) {
1423 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1424 * we must not try to free(bb_msg_unknown) */
1425 if (G.cwd == bb_msg_unknown)
1426 G.cwd = NULL;
1427 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1428 if (!G.cwd)
1429 G.cwd = bb_msg_unknown;
1430 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001431 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001432}
1433
Denis Vlasenko83506862007-11-23 13:11:42 +00001434
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001435/*
1436 * Shell and environment variable support
1437 */
1438static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001439{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001440 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001441 struct variable *cur;
1442 int len;
1443
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001444 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001445 pp = &G.top_var;
1446 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001447 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001448 return pp;
1449 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001450 }
1451 return NULL;
1452}
1453
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001454static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001455{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001456 struct variable **pp = get_ptr_to_local_var(name);
1457 if (pp)
1458 return *pp;
1459 return NULL;
1460}
1461
Denys Vlasenko03dad222010-01-12 23:29:57 +01001462static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001463{
Denys Vlasenko29082232010-07-16 13:52:32 +02001464 struct variable **vpp;
1465
1466 if (G.expanded_assignments) {
1467 char **cpp = G.expanded_assignments;
1468 int len = strlen(name);
1469 while (*cpp) {
1470 char *cp = *cpp;
1471 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1472 return cp + len + 1;
1473 cpp++;
1474 }
1475 }
1476
1477 vpp = get_ptr_to_local_var(name);
1478 if (vpp)
1479 return strchr((*vpp)->varstr, '=') + 1;
1480
Denys Vlasenkodea47882009-10-09 15:40:49 +02001481 if (strcmp(name, "PPID") == 0)
1482 return utoa(G.root_ppid);
1483 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001484#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001485 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001486 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001487 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001488#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001489 return NULL;
1490}
1491
1492/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001493 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001494 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001495 * 0: do not change export flag
1496 * (if creating new variable, flag will be 0)
1497 * 1: set export flag and putenv the variable
1498 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001499 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001500 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001501#if !BB_MMU && ENABLE_HUSH_LOCAL
1502/* all params are used */
1503#elif BB_MMU && ENABLE_HUSH_LOCAL
1504#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1505 set_local_var(str, flg_export, local_lvl)
1506#elif BB_MMU && !ENABLE_HUSH_LOCAL
1507#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001508 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001509#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1510#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1511 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001512#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001513static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001514{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001515 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001516 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001517 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001518 int name_len;
1519
Denis Vlasenko950bd722009-04-21 11:23:56 +00001520 eq_sign = strchr(str, '=');
1521 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001522 free(str);
1523 return -1;
1524 }
1525
Denis Vlasenko950bd722009-04-21 11:23:56 +00001526 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001527 var_pp = &G.top_var;
1528 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001529 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001530 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001531 continue;
1532 }
1533 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001534 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001535#if !BB_MMU
1536 if (!flg_read_only)
1537#endif
1538 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001539 free(str);
1540 return -1;
1541 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001542 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001543 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1544 *eq_sign = '\0';
1545 unsetenv(str);
1546 *eq_sign = '=';
1547 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001548#if ENABLE_HUSH_LOCAL
1549 if (cur->func_nest_level < local_lvl) {
1550 /* New variable is declared as local,
1551 * and existing one is global, or local
1552 * from enclosing function.
1553 * Remove and save old one: */
1554 *var_pp = cur->next;
1555 cur->next = *G.shadowed_vars_pp;
1556 *G.shadowed_vars_pp = cur;
1557 /* bash 3.2.33(1) and exported vars:
1558 * # export z=z
1559 * # f() { local z=a; env | grep ^z; }
1560 * # f
1561 * z=a
1562 * # env | grep ^z
1563 * z=z
1564 */
1565 if (cur->flg_export)
1566 flg_export = 1;
1567 break;
1568 }
1569#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001570 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001571 free_and_exp:
1572 free(str);
1573 goto exp;
1574 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001575 if (cur->max_len != 0) {
1576 if (cur->max_len >= strlen(str)) {
1577 /* This one is from startup env, reuse space */
1578 strcpy(cur->varstr, str);
1579 goto free_and_exp;
1580 }
1581 } else {
1582 /* max_len == 0 signifies "malloced" var, which we can
1583 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001584 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001585 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001586 cur->max_len = 0;
1587 goto set_str_and_exp;
1588 }
1589
Denys Vlasenko295fef82009-06-03 12:47:26 +02001590 /* Not found - create new variable struct */
1591 cur = xzalloc(sizeof(*cur));
1592#if ENABLE_HUSH_LOCAL
1593 cur->func_nest_level = local_lvl;
1594#endif
1595 cur->next = *var_pp;
1596 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001597
1598 set_str_and_exp:
1599 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001600#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001601 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001602#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001603 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001604 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001605 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001606 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1607 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001608 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001609 if (flg_export == -1) {
1610 cur->flg_export = 0;
1611 /* unsetenv was already done */
1612 } else {
1613 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1614 return putenv(cur->varstr);
1615 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001616 }
1617 return 0;
1618}
1619
Denys Vlasenko6db47842009-09-05 20:15:17 +02001620/* Used at startup and after each cd */
1621static void set_pwd_var(int exp)
1622{
1623 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1624 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1625}
1626
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001627static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001628{
1629 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001630 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001631
1632 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001633 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001634 var_pp = &G.top_var;
1635 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001636 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1637 if (cur->flg_read_only) {
1638 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001639 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001640 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001641 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001642 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1643 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001644 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1645 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001646 if (!cur->max_len)
1647 free(cur->varstr);
1648 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001649 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001650 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001651 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001652 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001653 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001654}
1655
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001656static int unset_local_var(const char *name)
1657{
1658 return unset_local_var_len(name, strlen(name));
1659}
1660
1661static void unset_vars(char **strings)
1662{
1663 char **v;
1664
1665 if (!strings)
1666 return;
1667 v = strings;
1668 while (*v) {
1669 const char *eq = strchrnul(*v, '=');
1670 unset_local_var_len(*v, (int)(eq - *v));
1671 v++;
1672 }
1673 free(strings);
1674}
1675
Mike Frysinger98c52642009-04-02 10:02:37 +00001676#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko8391c482010-05-22 17:50:43 +02001677# define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1678# define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denys Vlasenko03dad222010-01-12 23:29:57 +01001679static char* FAST_FUNC endofname(const char *name)
Mike Frysinger98c52642009-04-02 10:02:37 +00001680{
1681 char *p;
1682
1683 p = (char *) name;
1684 if (!is_name(*p))
1685 return p;
1686 while (*++p) {
1687 if (!is_in_name(*p))
1688 break;
1689 }
1690 return p;
1691}
Denys Vlasenko6b01b712010-01-24 22:52:21 +01001692#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001693
Denys Vlasenko03dad222010-01-12 23:29:57 +01001694static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001695{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001696 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001697 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001698}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001699
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001700
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001701/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001702 * Helpers for "var1=val1 var2=val2 cmd" feature
1703 */
1704static void add_vars(struct variable *var)
1705{
1706 struct variable *next;
1707
1708 while (var) {
1709 next = var->next;
1710 var->next = G.top_var;
1711 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001712 if (var->flg_export) {
1713 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001714 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001715 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001716 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001717 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001718 var = next;
1719 }
1720}
1721
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001722static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001723{
1724 char **s;
1725 struct variable *old = NULL;
1726
1727 if (!strings)
1728 return old;
1729 s = strings;
1730 while (*s) {
1731 struct variable *var_p;
1732 struct variable **var_pp;
1733 char *eq;
1734
1735 eq = strchr(*s, '=');
1736 if (eq) {
1737 *eq = '\0';
1738 var_pp = get_ptr_to_local_var(*s);
1739 *eq = '=';
1740 if (var_pp) {
1741 /* Remove variable from global linked list */
1742 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001743 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001744 *var_pp = var_p->next;
1745 /* Add it to returned list */
1746 var_p->next = old;
1747 old = var_p;
1748 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001749 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001750 }
1751 s++;
1752 }
1753 return old;
1754}
1755
1756
1757/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001758 * in_str support
1759 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001760static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001761{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001762 int ch = *i->p;
1763 if (ch != '\0') {
1764 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001765 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001766 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001767 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001768}
1769
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001770static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001771{
1772 return *i->p;
1773}
1774
1775#if ENABLE_HUSH_INTERACTIVE
1776
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001777static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001778{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001779 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001780 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001781 if (G.PS1 == NULL)
1782 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001783 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001784 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001785 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001786 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001787 if (G.PS2 == NULL)
1788 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001789}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001790
1791static const char* setup_prompt_string(int promptmode)
1792{
1793 const char *prompt_str;
1794 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001795 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1796 /* Set up the prompt */
1797 if (promptmode == 0) { /* PS1 */
1798 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001799 /* bash uses $PWD value, even if it is set by user.
1800 * It uses current dir only if PWD is unset.
1801 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001802 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001803 prompt_str = G.PS1;
1804 } else
1805 prompt_str = G.PS2;
1806 } else
1807 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001808 debug_printf("result '%s'\n", prompt_str);
1809 return prompt_str;
1810}
1811
1812static void get_user_input(struct in_str *i)
1813{
1814 int r;
1815 const char *prompt_str;
1816
1817 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001818# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001819 /* Enable command line editing only while a command line
1820 * is actually being read */
1821 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001822 G.flag_SIGINT = 0;
1823 /* buglet: SIGINT will not make new prompt to appear _at once_,
1824 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001825 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 +00001826 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001827 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001828 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001829 i->eof_flag = (r < 0);
1830 if (i->eof_flag) { /* EOF/error detected */
1831 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1832 G.user_input_buf[1] = '\0';
1833 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001834# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001835 do {
1836 G.flag_SIGINT = 0;
1837 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001838 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001839 G.user_input_buf[0] = r = fgetc(i->file);
1840 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001841//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001842 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001843 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001844# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001845 i->p = G.user_input_buf;
1846}
1847
1848#endif /* INTERACTIVE */
1849
1850/* This is the magic location that prints prompts
1851 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001852static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001853{
1854 int ch;
1855
1856 /* If there is data waiting, eat it up */
1857 if (i->p && *i->p) {
1858#if ENABLE_HUSH_INTERACTIVE
1859 take_cached:
1860#endif
1861 ch = *i->p++;
1862 if (i->eof_flag && !*i->p)
1863 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001864 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001865 } else {
1866 /* need to double check i->file because we might be doing something
1867 * more complicated by now, like sourcing or substituting. */
1868#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001869 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001870 do {
1871 get_user_input(i);
1872 } while (!*i->p); /* need non-empty line */
1873 i->promptmode = 1; /* PS2 */
1874 i->promptme = 0;
1875 goto take_cached;
1876 }
1877#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001878 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001879 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001880 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001881#if ENABLE_HUSH_INTERACTIVE
1882 if (ch == '\n')
1883 i->promptme = 1;
1884#endif
1885 return ch;
1886}
1887
Denis Vlasenko913a2012009-04-05 22:17:04 +00001888/* All callers guarantee this routine will never
1889 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001890 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001891static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001892{
1893 int ch;
1894 if (i->p && *i->p) {
1895 if (i->eof_flag && !i->p[1])
1896 return EOF;
1897 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001898 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001899 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001900 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001901 i->eof_flag = (ch == EOF);
1902 i->peek_buf[0] = ch;
1903 i->peek_buf[1] = '\0';
1904 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001905 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001906 return ch;
1907}
1908
1909static void setup_file_in_str(struct in_str *i, FILE *f)
1910{
1911 i->peek = file_peek;
1912 i->get = file_get;
1913#if ENABLE_HUSH_INTERACTIVE
1914 i->promptme = 1;
1915 i->promptmode = 0; /* PS1 */
1916#endif
1917 i->file = f;
1918 i->p = NULL;
1919}
1920
1921static void setup_string_in_str(struct in_str *i, const char *s)
1922{
1923 i->peek = static_peek;
1924 i->get = static_get;
1925#if ENABLE_HUSH_INTERACTIVE
1926 i->promptme = 1;
1927 i->promptmode = 0; /* PS1 */
1928#endif
1929 i->p = s;
1930 i->eof_flag = 0;
1931}
1932
1933
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001934/*
1935 * o_string support
1936 */
1937#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001938
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001939static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001940{
1941 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001942 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001943 if (o->data)
1944 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001945}
1946
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001947static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001948{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001949 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001950 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001951}
1952
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001953static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1954{
1955 free(o->data);
1956}
1957
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001958static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001959{
1960 if (o->length + len > o->maxlen) {
1961 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1962 o->data = xrealloc(o->data, 1 + o->maxlen);
1963 }
1964}
1965
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001966static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001967{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001968 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1969 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001970 o->data[o->length] = ch;
1971 o->length++;
1972 o->data[o->length] = '\0';
1973}
1974
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001975static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001976{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001977 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001978 memcpy(&o->data[o->length], str, len);
1979 o->length += len;
1980 o->data[o->length] = '\0';
1981}
1982
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001983static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001984{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001985 o_addblock(o, str, strlen(str));
1986}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02001987
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001988#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001989static void nommu_addchr(o_string *o, int ch)
1990{
1991 if (o)
1992 o_addchr(o, ch);
1993}
1994#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001995# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001996#endif
1997
1998static void o_addstr_with_NUL(o_string *o, const char *str)
1999{
2000 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002001}
2002
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002003static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00002004{
2005 while (len) {
2006 o_addchr(o, *str);
2007 if (*str++ == '\\'
2008 && (*str != '*' && *str != '?' && *str != '[')
2009 ) {
2010 o_addchr(o, '\\');
2011 }
2012 len--;
2013 }
2014}
2015
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002016#undef HUSH_BRACE_EXP
2017/*
2018 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2019 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2020 * Apparently, on unquoted $v bash still does globbing
2021 * ("v='*.txt'; echo $v" prints all .txt files),
2022 * but NOT brace expansion! Thus, there should be TWO independent
2023 * quoting mechanisms on $v expansion side: one protects
2024 * $v from brace expansion, and other additionally protects "$v" against globbing.
2025 * We have only second one.
2026 */
2027
2028#ifdef HUSH_BRACE_EXP
2029# define MAYBE_BRACES "{}"
2030#else
2031# define MAYBE_BRACES ""
2032#endif
2033
Eric Andersen25f27032001-04-26 23:22:31 +00002034/* My analysis of quoting semantics tells me that state information
2035 * is associated with a destination, not a source.
2036 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002037static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002038{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002039 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002040 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002041 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002042 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002043 o_grow_by(o, sz);
2044 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002045 o->data[o->length] = '\\';
2046 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002047 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002048 o->data[o->length] = ch;
2049 o->length++;
2050 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002051}
2052
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002053static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002054{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002055 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002056 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002057 sz++;
2058 o->data[o->length] = '\\';
2059 o->length++;
2060 }
2061 o_grow_by(o, sz);
2062 o->data[o->length] = ch;
2063 o->length++;
2064 o->data[o->length] = '\0';
2065}
2066
2067static void o_addQstr(o_string *o, const char *str, int len)
2068{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002069 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002070 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002071 return;
2072 }
2073 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002074 char ch;
2075 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002076 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002077 if (ordinary_cnt > len) /* paranoia */
2078 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002079 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002080 if (ordinary_cnt == len)
2081 return;
2082 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002083 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002084
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002085 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002086 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002087 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002088 sz++;
2089 o->data[o->length] = '\\';
2090 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002091 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002092 o_grow_by(o, sz);
2093 o->data[o->length] = ch;
2094 o->length++;
2095 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002096 }
2097}
2098
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002099/* A special kind of o_string for $VAR and `cmd` expansion.
2100 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002101 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002102 * list[i] contains an INDEX (int!) into this string data.
2103 * It means that if list[] needs to grow, data needs to be moved higher up
2104 * but list[i]'s need not be modified.
2105 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002106 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002107 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2108 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002109#if DEBUG_EXPAND || DEBUG_GLOB
2110static void debug_print_list(const char *prefix, o_string *o, int n)
2111{
2112 char **list = (char**)o->data;
2113 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2114 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002115
2116 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002117 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
2118 prefix, list, n, string_start, o->length, o->maxlen);
2119 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002120 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002121 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2122 o->data + (int)list[i] + string_start,
2123 o->data + (int)list[i] + string_start);
2124 i++;
2125 }
2126 if (n) {
2127 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002128 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002129 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002130 }
2131}
2132#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002133# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002134#endif
2135
2136/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2137 * in list[n] so that it points past last stored byte so far.
2138 * It returns n+1. */
2139static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002140{
2141 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002142 int string_start;
2143 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002144
2145 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002146 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2147 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002148 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002149 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002150 /* list[n] points to string_start, make space for 16 more pointers */
2151 o->maxlen += 0x10 * sizeof(list[0]);
2152 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002153 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002154 memmove(list + n + 0x10, list + n, string_len);
2155 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002156 } else {
2157 debug_printf_list("list[%d]=%d string_start=%d\n",
2158 n, string_len, string_start);
2159 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002160 } else {
2161 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002162 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2163 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002164 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2165 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002166 o->has_empty_slot = 0;
2167 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002168 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002169 return n + 1;
2170}
2171
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002172/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002173static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002174{
2175 char **list = (char**)o->data;
2176 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2177
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002178 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002179}
2180
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002181#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002182/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2183 * first, it processes even {a} (no commas), second,
2184 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002185 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002186 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002187
2188/* Helper */
2189static int glob_needed(const char *s)
2190{
2191 while (*s) {
2192 if (*s == '\\') {
2193 if (!s[1])
2194 return 0;
2195 s += 2;
2196 continue;
2197 }
2198 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2199 return 1;
2200 s++;
2201 }
2202 return 0;
2203}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002204/* Return pointer to next closing brace or to comma */
2205static const char *next_brace_sub(const char *cp)
2206{
2207 unsigned depth = 0;
2208 cp++;
2209 while (*cp != '\0') {
2210 if (*cp == '\\') {
2211 if (*++cp == '\0')
2212 break;
2213 cp++;
2214 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002215 }
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002216 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2217 break;
2218 if (*cp++ == '{') /*}*/
2219 depth++;
2220 }
2221
2222 return *cp != '\0' ? cp : NULL;
2223}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002224/* Recursive brace globber. Note: may garble pattern[]. */
2225static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002226{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002227 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002228 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002229 const char *next;
2230 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002231 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002232 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002233
2234 debug_printf_glob("glob_brace('%s')\n", pattern);
2235
2236 begin = pattern;
2237 while (1) {
2238 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002239 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002240 if (*begin == '{') /*}*/ {
2241 /* Find the first sub-pattern and at the same time
2242 * find the rest after the closing brace */
2243 next = next_brace_sub(begin);
2244 if (next == NULL) {
2245 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002246 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002247 }
2248 /*{*/ if (*next == '}') {
2249 /* "{abc}" with no commas - illegal
2250 * brace expr, disregard and skip it */
2251 begin = next + 1;
2252 continue;
2253 }
2254 break;
2255 }
2256 if (*begin == '\\' && begin[1] != '\0')
2257 begin++;
2258 begin++;
2259 }
2260 debug_printf_glob("begin:%s\n", begin);
2261 debug_printf_glob("next:%s\n", next);
2262
2263 /* Now find the end of the whole brace expression */
2264 rest = next;
2265 /*{*/ while (*rest != '}') {
2266 rest = next_brace_sub(rest);
2267 if (rest == NULL) {
2268 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002269 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002270 }
2271 debug_printf_glob("rest:%s\n", rest);
2272 }
2273 rest_len = strlen(++rest) + 1;
2274
2275 /* We are sure the brace expression is well-formed */
2276
2277 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002278 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002279
2280 /* We have a brace expression. BEGIN points to the opening {,
2281 * NEXT points past the terminator of the first element, and REST
2282 * points past the final }. We will accumulate result names from
2283 * recursive runs for each brace alternative in the buffer using
2284 * GLOB_APPEND. */
2285
2286 p = begin + 1;
2287 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002288 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002289 memcpy(
2290 mempcpy(
2291 mempcpy(new_pattern_buf,
2292 /* We know the prefix for all sub-patterns */
2293 pattern, begin - pattern),
2294 p, next - p),
2295 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002296
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002297 /* Note: glob_brace() may garble new_pattern_buf[].
2298 * That's why we re-copy prefix every time (1st memcpy above).
2299 */
2300 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002301 /*{*/ if (*next == '}') {
2302 /* We saw the last entry */
2303 break;
2304 }
2305 p = next + 1;
2306 next = next_brace_sub(next);
2307 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002308 free(new_pattern_buf);
2309 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002310
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002311 simple_glob:
2312 {
2313 int gr;
2314 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002315
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002316 memset(&globdata, 0, sizeof(globdata));
2317 gr = glob(pattern, 0, NULL, &globdata);
2318 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2319 if (gr != 0) {
2320 if (gr == GLOB_NOMATCH) {
2321 globfree(&globdata);
2322 /* NB: garbles parameter */
2323 unbackslash(pattern);
2324 o_addstr_with_NUL(o, pattern);
2325 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2326 return o_save_ptr_helper(o, n);
2327 }
2328 if (gr == GLOB_NOSPACE)
2329 bb_error_msg_and_die(bb_msg_memory_exhausted);
2330 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2331 * but we didn't specify it. Paranoia again. */
2332 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2333 }
2334 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2335 char **argv = globdata.gl_pathv;
2336 while (1) {
2337 o_addstr_with_NUL(o, *argv);
2338 n = o_save_ptr_helper(o, n);
2339 argv++;
2340 if (!*argv)
2341 break;
2342 }
2343 }
2344 globfree(&globdata);
2345 }
2346 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002347}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002348/* Performs globbing on last list[],
2349 * saving each result as a new list[].
2350 */
2351static int o_glob(o_string *o, int n)
2352{
2353 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002354
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002355 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2356 if (!o->data)
2357 return o_save_ptr_helper(o, n);
2358 pattern = o->data + o_get_last_ptr(o, n);
2359 debug_printf_glob("glob pattern '%s'\n", pattern);
2360 if (!glob_needed(pattern)) {
2361 /* unbackslash last string in o in place, fix length */
2362 o->length = unbackslash(pattern) - o->data;
2363 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2364 return o_save_ptr_helper(o, n);
2365 }
2366
2367 copy = xstrdup(pattern);
2368 /* "forget" pattern in o */
2369 o->length = pattern - o->data;
2370 n = glob_brace(copy, o, n);
2371 free(copy);
2372 if (DEBUG_GLOB)
2373 debug_print_list("o_glob returning", o, n);
2374 return n;
2375}
2376
Denys Vlasenko8391c482010-05-22 17:50:43 +02002377#else /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002378
2379/* Helper */
2380static int glob_needed(const char *s)
2381{
2382 while (*s) {
2383 if (*s == '\\') {
2384 if (!s[1])
2385 return 0;
2386 s += 2;
2387 continue;
2388 }
2389 if (*s == '*' || *s == '[' || *s == '?')
2390 return 1;
2391 s++;
2392 }
2393 return 0;
2394}
2395/* Performs globbing on last list[],
2396 * saving each result as a new list[].
2397 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002398static int o_glob(o_string *o, int n)
2399{
2400 glob_t globdata;
2401 int gr;
2402 char *pattern;
2403
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002404 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002405 if (!o->data)
2406 return o_save_ptr_helper(o, n);
2407 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002408 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002409 if (!glob_needed(pattern)) {
2410 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002411 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002412 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002413 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002414 return o_save_ptr_helper(o, n);
2415 }
2416
2417 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002418 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2419 * If we glob "*.\*" and don't find anything, we need
2420 * to fall back to using literal "*.*", but GLOB_NOCHECK
2421 * will return "*.\*"!
2422 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002423 gr = glob(pattern, 0, NULL, &globdata);
2424 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002425 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002426 if (gr == GLOB_NOMATCH) {
2427 globfree(&globdata);
2428 goto literal;
2429 }
2430 if (gr == GLOB_NOSPACE)
2431 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002432 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2433 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002434 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002435 }
2436 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2437 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002438 /* "forget" pattern in o */
2439 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002440 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002441 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002442 n = o_save_ptr_helper(o, n);
2443 argv++;
2444 if (!*argv)
2445 break;
2446 }
2447 }
2448 globfree(&globdata);
2449 if (DEBUG_GLOB)
2450 debug_print_list("o_glob returning", o, n);
2451 return n;
2452}
2453
Denys Vlasenko8391c482010-05-22 17:50:43 +02002454#endif /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002455
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002456/* If o->o_glob == 1, glob the string so far remembered.
2457 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002458static int o_save_ptr(o_string *o, int n)
2459{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002460 if (o->o_glob) { /* if globbing is requested */
2461 /* If o->has_empty_slot, list[n] was already globbed
2462 * (if it was requested back then when it was filled)
2463 * so don't do that again! */
2464 if (!o->has_empty_slot)
2465 return o_glob(o, n); /* o_save_ptr_helper is inside */
2466 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002467 return o_save_ptr_helper(o, n);
2468}
2469
2470/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002471static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002472{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002473 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002474 int string_start;
2475
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002476 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2477 if (DEBUG_EXPAND)
2478 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002479 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002480 list = (char**)o->data;
2481 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2482 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002483 while (n) {
2484 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002485 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002486 }
2487 return list;
2488}
2489
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002490
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002491/* Expansion can recurse */
2492#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002493static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002494#endif
2495static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002496#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002497#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002498 parse_stream_dquoted(dest, input, dquote_end)
2499#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002500static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002501 o_string *dest,
2502 struct in_str *input,
2503 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002504
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002505/* expand_strvec_to_strvec() takes a list of strings, expands
2506 * all variable references within and returns a pointer to
2507 * a list of expanded strings, possibly with larger number
2508 * of strings. (Think VAR="a b"; echo $VAR).
2509 * This new list is allocated as a single malloc block.
2510 * NULL-terminated list of char* pointers is at the beginning of it,
2511 * followed by strings themself.
2512 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002513
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002514/* Store given string, finalizing the word and starting new one whenever
2515 * we encounter IFS char(s). This is used for expanding variable values.
2516 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2517static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002518{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002519 while (1) {
2520 int word_len = strcspn(str, G.ifs);
2521 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002522 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002523 o_addQstr(output, str, word_len);
2524 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002525 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002526 str += word_len;
2527 }
2528 if (!*str) /* EOL - do not finalize word */
2529 break;
2530 o_addchr(output, '\0');
2531 debug_print_list("expand_on_ifs", output, n);
2532 n = o_save_ptr(output, n);
2533 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002534 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002535 debug_print_list("expand_on_ifs[1]", output, n);
2536 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002537}
2538
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002539/* Helper to expand $((...)) and heredoc body. These act as if
2540 * they are in double quotes, with the exception that they are not :).
2541 * Just the rules are similar: "expand only $var and `cmd`"
2542 *
2543 * Returns malloced string.
2544 * As an optimization, we return NULL if expansion is not needed.
2545 */
2546static char *expand_pseudo_dquoted(const char *str)
2547{
2548 char *exp_str;
2549 struct in_str input;
2550 o_string dest = NULL_O_STRING;
2551
2552 if (strchr(str, '$') == NULL
2553#if ENABLE_HUSH_TICK
2554 && strchr(str, '`') == NULL
2555#endif
2556 ) {
2557 return NULL;
2558 }
2559
2560 /* We need to expand. Example:
2561 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2562 */
2563 setup_string_in_str(&input, str);
2564 parse_stream_dquoted(NULL, &dest, &input, EOF);
2565 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2566 exp_str = expand_string_to_string(dest.data);
2567 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2568 o_free_unsafe(&dest);
2569 return exp_str;
2570}
2571
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002572#if ENABLE_SH_MATH_SUPPORT
2573static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2574{
2575 arith_eval_hooks_t hooks;
2576 arith_t res;
2577 char *exp_str;
2578
2579 hooks.lookupvar = get_local_var_value;
2580 hooks.setvar = set_local_var_from_halves;
2581 hooks.endofname = endofname;
2582 exp_str = expand_pseudo_dquoted(arg);
2583 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2584 free(exp_str);
2585 return res;
2586}
2587#endif
2588
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002589/* Expand all variable references in given string, adding words to list[]
2590 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2591 * to be filled). This routine is extremely tricky: has to deal with
2592 * variables/parameters with whitespace, $* and $@, and constructs like
2593 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02002594static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002595{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002596 /* or_mask is either 0 (normal case) or 0x80 -
2597 * expansion of right-hand side of assignment == 1-element expand.
2598 * It will also do no globbing, and thus we must not backslash-quote!
2599 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002600 char ored_ch;
2601 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002602
2603 ored_ch = 0;
2604
Denys Vlasenkof37eb392009-10-18 11:46:35 +02002605 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002606 debug_print_list("expand_vars_to_list", output, n);
2607 n = o_save_ptr(output, n);
2608 debug_print_list("expand_vars_to_list[0]", output, n);
2609
2610 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002611 char first_ch;
2612 int i;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002613 char *to_be_freed = NULL;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002614 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002615#if ENABLE_HUSH_TICK
2616 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002617#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002618#if ENABLE_SH_MATH_SUPPORT
2619 char arith_buf[sizeof(arith_t)*3 + 2];
2620#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002621 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002622 debug_print_list("expand_vars_to_list[1]", output, n);
2623 arg = ++p;
2624 p = strchr(p, SPECIAL_VAR_SYMBOL);
2625
2626 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2627 /* "$@" is special. Even if quoted, it can still
2628 * expand to nothing (not even an empty string) */
2629 if ((first_ch & 0x7f) != '@')
2630 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002631
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002632 switch (first_ch & 0x7f) {
2633 /* Highest bit in first_ch indicates that var is double-quoted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002634 case '*':
2635 case '@':
2636 i = 1;
2637 if (!G.global_argv[i])
2638 break;
2639 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2640 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002641 smallint sv = output->o_escape;
2642 /* unquoted var's contents should be globbed, so don't escape */
2643 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002644 while (G.global_argv[i]) {
2645 n = expand_on_ifs(output, n, G.global_argv[i]);
2646 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2647 if (G.global_argv[i++][0] && G.global_argv[i]) {
2648 /* this argv[] is not empty and not last:
2649 * put terminating NUL, start new word */
2650 o_addchr(output, '\0');
2651 debug_print_list("expand_vars_to_list[2]", output, n);
2652 n = o_save_ptr(output, n);
2653 debug_print_list("expand_vars_to_list[3]", output, n);
2654 }
2655 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002656 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002657 } else
2658 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2659 * and in this case should treat it like '$*' - see 'else...' below */
2660 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2661 while (1) {
2662 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2663 if (++i >= G.global_argc)
2664 break;
2665 o_addchr(output, '\0');
2666 debug_print_list("expand_vars_to_list[4]", output, n);
2667 n = o_save_ptr(output, n);
2668 }
2669 } else { /* quoted $*: add as one word */
2670 while (1) {
2671 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2672 if (!G.global_argv[++i])
2673 break;
2674 if (G.ifs[0])
2675 o_addchr(output, G.ifs[0]);
2676 }
2677 }
2678 break;
2679 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2680 /* "Empty variable", used to make "" etc to not disappear */
2681 arg++;
2682 ored_ch = 0x80;
2683 break;
2684#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002685 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002686 *p = '\0';
2687 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002688 /* Can't just stuff it into output o_string,
2689 * expanded result may need to be globbed
2690 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002691 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko647553a2009-11-15 19:58:19 +01002692 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenkocddbb612010-05-20 14:27:09 +02002693 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002694 val = subst_result.data;
2695 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002696#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002697#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002698 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002699 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002700 int errcode;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002701
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002702 arg++; /* skip '+' */
2703 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002704 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002705 res = expand_and_evaluate_arith(arg, &errcode);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002706
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002707 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002708 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002709 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002710 case -3:
2711 msg = "exponent less than 0";
2712 break;
2713 case -2:
2714 msg = "divide by 0";
2715 break;
2716 case -5:
2717 msg = "expression recursion loop detected";
2718 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002719 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002720 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002721 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002722 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002723 sprintf(arith_buf, arith_t_fmt, res);
2724 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002725 break;
2726 }
2727#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002728 default: { /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2729 char *var;
2730 char first_char;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002731 char exp_op;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002732 char exp_save = exp_save; /* for compiler */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002733 char *exp_saveptr; /* points to expansion operator */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002734 char *exp_word = exp_word; /* for compiler */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002735
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002736 var = arg;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002737 *p = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002738 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2739 first_char = arg[0] = first_ch & 0x7f;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002740 exp_op = 0;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002741
2742 if (first_char == '#' && arg[1] && !exp_saveptr) {
Mike Frysinger6379bb42009-03-28 18:55:03 +00002743 /* handle length expansion ${#var} */
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002744 var++;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002745 exp_op = 'L';
Mike Frysinger6379bb42009-03-28 18:55:03 +00002746 } else {
2747 /* maybe handle parameter expansion */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002748 if (exp_saveptr /* if 2nd char is one of expansion operators */
2749 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2750 ) {
2751 /* ${?:0}, ${#[:]%0} etc */
2752 exp_saveptr = var + 1;
2753 } else {
2754 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2755 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2756 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002757 exp_op = exp_save = *exp_saveptr;
2758 if (exp_op) {
2759 exp_word = exp_saveptr + 1;
2760 if (exp_op == ':') {
2761 exp_op = *exp_word++;
2762 if (ENABLE_HUSH_BASH_COMPAT
2763 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2764 ) {
2765 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2766 exp_op = ':';
2767 exp_word--;
2768 }
2769 }
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002770 *exp_saveptr = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002771 } /* else: it's not an expansion op, but bare ${var} */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002772 }
2773
2774 /* lookup the variable in question */
2775 if (isdigit(var[0])) {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002776 /* parse_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002777 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002778 if (i < G.global_argc)
2779 val = G.global_argv[i];
2780 /* else val remains NULL: $N with too big N */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002781 } else {
2782 switch (var[0]) {
2783 case '$': /* pid */
2784 val = utoa(G.root_pid);
2785 break;
2786 case '!': /* bg pid */
2787 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2788 break;
2789 case '?': /* exitcode */
2790 val = utoa(G.last_exitcode);
2791 break;
2792 case '#': /* argc */
2793 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2794 break;
2795 default:
2796 val = get_local_var_value(var);
2797 }
2798 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002799
2800 /* handle any expansions */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002801 if (exp_op == 'L') {
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002802 debug_printf_expand("expand: length(%s)=", val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002803 val = utoa(val ? strlen(val) : 0);
2804 debug_printf_expand("%s\n", val);
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002805 } else if (exp_op) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002806 if (exp_op == '%' || exp_op == '#') {
Denys Vlasenko53b51332010-05-20 21:46:45 +02002807 /* Standard-mandated substring removal ops:
2808 * ${parameter%word} - remove smallest suffix pattern
2809 * ${parameter%%word} - remove largest suffix pattern
2810 * ${parameter#word} - remove smallest prefix pattern
2811 * ${parameter##word} - remove largest prefix pattern
2812 *
2813 * Word is expanded to produce a glob pattern.
2814 * Then var's value is matched to it and matching part removed.
2815 */
Mike Frysinger57e74672009-04-09 23:00:33 +00002816 if (val) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002817 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002818 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002819 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002820 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002821 exp_word++;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002822 val = to_be_freed = xstrdup(val);
Denys Vlasenko74369502010-05-21 19:52:01 +02002823 {
2824 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2825 if (exp_exp_word)
2826 exp_word = exp_exp_word;
2827 loc = scan(to_be_freed, exp_word, match_at_left);
2828 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2829 // exp_op, to_be_freed, exp_word, loc);
2830 free(exp_exp_word);
2831 }
2832 if (loc) { /* match was found */
2833 if (match_at_left) /* # or ## */
2834 val = loc;
2835 else /* % or %% */
2836 *loc = '\0';
2837 }
Mike Frysinger57e74672009-04-09 23:00:33 +00002838 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002839 } else if (exp_op == ':') {
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02002840#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002841 /* It's ${var:N[:M]} bashism.
2842 * Note that in encoded form it has TWO parts:
2843 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002844 */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002845 arith_t beg, len;
2846 int errcode = 0;
2847
2848 beg = expand_and_evaluate_arith(exp_word, &errcode);
2849 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2850 *p++ = SPECIAL_VAR_SYMBOL;
2851 exp_word = p;
2852 p = strchr(p, SPECIAL_VAR_SYMBOL);
2853 *p = '\0';
2854 len = expand_and_evaluate_arith(exp_word, &errcode);
2855 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2856
2857 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2858 if (beg < 0) /* bash compat */
2859 beg = 0;
2860 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002861 if (len == 0 || !val || beg >= strlen(val))
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002862 val = "";
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002863 else {
2864 /* Paranoia. What if user entered 9999999999999
2865 * which fits in arith_t but not int? */
2866 if (len >= INT_MAX)
2867 len = INT_MAX;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002868 val = to_be_freed = xstrndup(val + beg, len);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002869 }
2870 debug_printf_varexp("val:'%s'\n", val);
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002871 } else
2872#endif
2873 {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002874 die_if_script("malformed ${%s:...}", var);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002875 val = "";
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002876 }
2877 } else { /* one of "-=+?" */
Denys Vlasenko53b51332010-05-20 21:46:45 +02002878 /* Standard-mandated substitution ops:
2879 * ${var?word} - indicate error if unset
2880 * If var is unset, word (or a message indicating it is unset
2881 * if word is null) is written to standard error
2882 * and the shell exits with a non-zero exit status.
2883 * Otherwise, the value of var is substituted.
2884 * ${var-word} - use default value
2885 * If var is unset, word is substituted.
2886 * ${var=word} - assign and use default value
2887 * If var is unset, word is assigned to var.
2888 * In all cases, final value of var is substituted.
2889 * ${var+word} - use alternative value
2890 * If var is unset, null is substituted.
2891 * Otherwise, word is substituted.
2892 *
2893 * Word is subjected to tilde expansion, parameter expansion,
2894 * command substitution, and arithmetic expansion.
2895 * If word is not needed, it is not expanded.
2896 *
2897 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2898 * but also treat null var as if it is unset.
2899 */
2900 int use_word = (!val || ((exp_save == ':') && !val[0]));
Mike Frysingera4f331d2009-04-07 06:03:22 +00002901 if (exp_op == '+')
Denys Vlasenko53b51332010-05-20 21:46:45 +02002902 use_word = !use_word;
Mike Frysingera4f331d2009-04-07 06:03:22 +00002903 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
Denys Vlasenko53b51332010-05-20 21:46:45 +02002904 (exp_save == ':') ? "true" : "false", use_word);
2905 if (use_word) {
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002906 to_be_freed = expand_pseudo_dquoted(exp_word);
2907 if (to_be_freed)
2908 exp_word = to_be_freed;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002909 if (exp_op == '?') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002910 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002911 die_if_script("%s: %s",
2912 var,
2913 exp_word[0] ? exp_word : "parameter null or not set"
2914 );
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002915//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002916 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002917 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002918 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002919
Mike Frysingera4f331d2009-04-07 06:03:22 +00002920 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002921 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002922 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002923 /* mimic bash message */
2924 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002925 val = NULL;
2926 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002927 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002928 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002929 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002930 }
2931 }
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002932 } /* one of "-=+?" */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002933
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002934 *exp_saveptr = exp_save;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002935 } /* if (exp_op) */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002936
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002937 arg[0] = first_ch;
2938#if ENABLE_HUSH_TICK
2939 store_val:
2940#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002941 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002942 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002943 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002944 /* unquoted var's contents should be globbed, so don't escape */
2945 smallint sv = output->o_escape;
2946 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002947 n = expand_on_ifs(output, n, val);
2948 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002949 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002950 }
2951 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002952 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002953 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002954 } /* default: */
2955 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002956
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002957 if (val) {
2958 o_addQstr(output, val, strlen(val));
2959 }
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002960 free(to_be_freed);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002961 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002962 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002963 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002964
2965#if ENABLE_HUSH_TICK
2966 o_free(&subst_result);
2967#endif
2968 arg = ++p;
2969 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2970
2971 if (arg[0]) {
2972 debug_print_list("expand_vars_to_list[a]", output, n);
2973 /* this part is literal, and it was already pre-quoted
2974 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002975 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002976 debug_print_list("expand_vars_to_list[b]", output, n);
2977 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2978 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2979 ) {
2980 n--;
2981 /* allow to reuse list[n] later without re-growth */
2982 output->has_empty_slot = 1;
2983 } else {
2984 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002985 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002986 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002987}
2988
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002989static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002990{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002991 int n;
2992 char **list;
2993 char **v;
2994 o_string output = NULL_O_STRING;
2995
2996 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002997 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002998 /* (unquoted $var will temporarily switch it off) */
2999 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003000 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003001
3002 n = 0;
3003 v = argv;
3004 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003005 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003006 v++;
3007 }
3008 debug_print_list("expand_variables", &output, n);
3009
3010 /* output.data (malloced in one block) gets returned in "list" */
3011 list = o_finalize_list(&output, n);
3012 debug_print_strings("expand_variables[1]", list);
3013 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00003014}
3015
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003016static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003017{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003018 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00003019}
3020
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003021#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003022static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3023{
3024 return expand_variables(argv, 0x80);
3025}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003026#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003027
3028#ifdef CMD_SINGLEWORD_NOGLOB_COND
3029static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3030{
3031 int n;
3032 char **list;
3033 char **v;
3034 o_string output = NULL_O_STRING;
3035
3036 n = 0;
3037 v = argv;
3038 while (*v) {
3039 int is_var = is_well_formed_var_name(*v, '=');
3040 /* is_var * 0x80: singleword expansion for vars */
3041 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3042
3043 /* Subtle! expand_vars_to_list did not glob last word yet.
3044 * It does this only when fed with further data.
3045 * Therefore we set globbing flags AFTER it, not before:
3046 */
3047
3048 /* if it is not recognizably abc=...; then: */
3049 output.o_escape = !is_var; /* protect against globbing for "$var" */
3050 /* (unquoted $var will temporarily switch it off) */
3051 output.o_glob = !is_var; /* and indeed do globbing */
3052 v++;
3053 }
3054 debug_print_list("expand_cond", &output, n);
3055
3056 /* output.data (malloced in one block) gets returned in "list" */
3057 list = o_finalize_list(&output, n);
3058 debug_print_strings("expand_cond[1]", list);
3059 return list;
3060}
3061#endif
3062
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003063/* Used for expansion of right hand of assignments */
3064/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
3065 * "v=/bin/c*" */
3066static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00003067{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003068 char *argv[2], **list;
3069
3070 argv[0] = (char*)str;
3071 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003072 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003073 if (HUSH_DEBUG)
3074 if (!list[0] || list[1])
3075 bb_error_msg_and_die("BUG in varexp2");
3076 /* actually, just move string 2*sizeof(char*) bytes back */
3077 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003078 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003079 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3080 return (char*)list;
3081}
3082
3083/* Used for "eval" builtin */
3084static char* expand_strvec_to_string(char **argv)
3085{
3086 char **list;
3087
3088 list = expand_variables(argv, 0x80);
3089 /* Convert all NULs to spaces */
3090 if (list[0]) {
3091 int n = 1;
3092 while (list[n]) {
3093 if (HUSH_DEBUG)
3094 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3095 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003096 /* bash uses ' ' regardless of $IFS contents */
3097 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003098 n++;
3099 }
3100 }
3101 overlapping_strcpy((char*)list, list[0]);
3102 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3103 return (char*)list;
3104}
3105
3106static char **expand_assignments(char **argv, int count)
3107{
3108 int i;
Denys Vlasenko29082232010-07-16 13:52:32 +02003109 char **p;
3110
3111 G.expanded_assignments = p = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003112 /* Expand assignments into one string each */
3113 for (i = 0; i < count; i++) {
Denys Vlasenko29082232010-07-16 13:52:32 +02003114 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003115 }
Denys Vlasenko29082232010-07-16 13:52:32 +02003116 G.expanded_assignments = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003117 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00003118}
3119
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003120
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003121#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003122/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003123void re_execute_shell(char ***to_free, const char *s,
3124 char *g_argv0, char **g_argv,
3125 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003126
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003127static void reset_traps_to_defaults(void)
3128{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003129 /* This function is always called in a child shell
3130 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003131 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003132 unsigned sig;
3133 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003134
Denys Vlasenko67f71862009-09-25 14:21:06 +02003135 /* Child shells are not interactive.
3136 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3137 * Testcase: (while :; do :; done) + ^Z should background.
3138 * Same goes for SIGTERM, SIGHUP, SIGINT.
3139 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003140 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02003141 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003142
Denys Vlasenko67f71862009-09-25 14:21:06 +02003143 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3144 * Stupid. It can be done with *single* &= op, but we can't use
3145 * the fact that G.blocked_set is implemented as a bitmask
3146 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003147 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3148 sig = 1;
3149 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02003150 if (mask & 1) {
3151 /* Careful. Only if no trap or trap is not "" */
3152 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3153 sigdelset(&G.blocked_set, sig);
3154 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003155 mask >>= 1;
3156 if (!mask)
3157 break;
3158 sig++;
3159 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02003160 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003161 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003162
3163 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003164 mask = G.non_DFL_mask;
3165 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02003166 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003167 continue;
3168 free(G.traps[sig]);
3169 G.traps[sig] = NULL;
3170 /* There is no signal for 0 (EXIT) */
3171 if (sig == 0)
3172 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003173 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003174 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02003175 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003176 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003177 continue;
3178 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003179 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003180 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003181}
3182
3183#else /* !BB_MMU */
3184
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003185static void re_execute_shell(char ***to_free, const char *s,
3186 char *g_argv0, char **g_argv,
3187 char **builtin_argv) NORETURN;
3188static void re_execute_shell(char ***to_free, const char *s,
3189 char *g_argv0, char **g_argv,
3190 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003191{
Denys Vlasenko8391c482010-05-22 17:50:43 +02003192# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003193 /* delims + 2 * (number of bytes in printed hex numbers) */
3194 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003195 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003196 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003197# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003198 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003199# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003200 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003201 unsigned cnt;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003202 unsigned long long empty_trap_mask;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003203
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003204 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003205 argv = heredoc_argv;
3206 argv[0] = (char *) G.argv0_for_re_execing;
3207 argv[1] = (char *) "-<";
3208 argv[2] = (char *) s;
3209 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00003210 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003211 goto do_exec;
3212 }
3213
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003214 cnt = 0;
3215 pp = builtin_argv;
3216 if (pp) while (*pp++)
3217 cnt++;
3218
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003219 empty_trap_mask = 0;
3220 if (G.traps) {
3221 int sig;
3222 for (sig = 1; sig < NSIG; sig++) {
3223 if (G.traps[sig] && !G.traps[sig][0])
3224 empty_trap_mask |= 1LL << sig;
3225 }
3226 }
3227
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003228 sprintf(param_buf, NOMMU_HACK_FMT
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003229 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02003230 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003231 , (unsigned) G.last_bg_pid
3232 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003233 , cnt
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003234 , empty_trap_mask
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003235 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003236 );
Denys Vlasenko8391c482010-05-22 17:50:43 +02003237# undef NOMMU_HACK_FMT
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003238 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003239 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003240 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003241 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003242 for (cur = G.top_var; cur; cur = cur->next) {
3243 if (!cur->flg_export || cur->flg_read_only)
3244 cnt += 2;
3245 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003246# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003247 for (funcp = G.top_func; funcp; funcp = funcp->next)
3248 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003249# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003250 pp = g_argv;
3251 while (*pp++)
3252 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003253 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003254 *pp++ = (char *) G.argv0_for_re_execing;
3255 *pp++ = param_buf;
3256 for (cur = G.top_var; cur; cur = cur->next) {
3257 if (cur->varstr == hush_version_str)
3258 continue;
3259 if (cur->flg_read_only) {
3260 *pp++ = (char *) "-R";
3261 *pp++ = cur->varstr;
3262 } else if (!cur->flg_export) {
3263 *pp++ = (char *) "-V";
3264 *pp++ = cur->varstr;
3265 }
3266 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003267# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003268 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3269 *pp++ = (char *) "-F";
3270 *pp++ = funcp->name;
3271 *pp++ = funcp->body_as_string;
3272 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003273# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003274 /* We can pass activated traps here. Say, -Tnn:trap_string
3275 *
3276 * However, POSIX says that subshells reset signals with traps
3277 * to SIG_DFL.
3278 * I tested bash-3.2 and it not only does that with true subshells
3279 * of the form ( list ), but with any forked children shells.
3280 * I set trap "echo W" WINCH; and then tried:
3281 *
3282 * { echo 1; sleep 20; echo 2; } &
3283 * while true; do echo 1; sleep 20; echo 2; break; done &
3284 * true | { echo 1; sleep 20; echo 2; } | cat
3285 *
3286 * In all these cases sending SIGWINCH to the child shell
3287 * did not run the trap. If I add trap "echo V" WINCH;
3288 * _inside_ group (just before echo 1), it works.
3289 *
3290 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003291 * Even if we would use signal handlers instead of signal masking
3292 * in order to implement trap handling,
3293 * exec syscall below resets signals to SIG_DFL for us.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003294 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003295 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003296 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003297 if (builtin_argv) {
3298 while (*++builtin_argv)
3299 *pp++ = *builtin_argv;
3300 *pp++ = (char *) "";
3301 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003302 *pp++ = g_argv0;
3303 while (*g_argv)
3304 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003305 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003306 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003307
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003308 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003309 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3310 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003311 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003312 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003313 if (argv[0][0] == '/')
3314 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003315 xfunc_error_retval = 127;
3316 bb_error_msg_and_die("can't re-execute the shell");
3317}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003318#endif /* !BB_MMU */
3319
3320
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003321static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003322{
3323 struct fd_pair pair;
3324 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003325 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003326 /* the _body_ of heredoc (misleading field name) */
3327 const char *heredoc = redir->rd_filename;
3328 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003329#if !BB_MMU
3330 char **to_free;
3331#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003332
3333 expanded = NULL;
3334 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3335 expanded = expand_pseudo_dquoted(heredoc);
3336 if (expanded)
3337 heredoc = expanded;
3338 }
3339 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003340
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003341 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003342 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003343 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003344
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003345 /* Try writing without forking. Newer kernels have
3346 * dynamically growing pipes. Must use non-blocking write! */
3347 ndelay_on(pair.wr);
3348 while (1) {
3349 written = write(pair.wr, heredoc, len);
3350 if (written <= 0)
3351 break;
3352 len -= written;
3353 if (len == 0) {
3354 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00003355 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003356 return;
3357 }
3358 heredoc += written;
3359 }
3360 ndelay_off(pair.wr);
3361
3362 /* Okay, pipe buffer was not big enough */
3363 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003364 * for the unsuspecting parent process. Child creates a grandchild
3365 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003366 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003367#if !BB_MMU
3368 to_free = NULL;
3369#endif
Pascal Bellard926031b2010-07-04 15:32:38 +02003370 pid = xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003371 if (pid == 0) {
3372 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003373 disable_restore_tty_pgrp_on_exit();
Pascal Bellard926031b2010-07-04 15:32:38 +02003374 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003375 if (pid != 0)
3376 _exit(0);
3377 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003378 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003379#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003380 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003381 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003382#else
3383 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003384 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003385 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003386#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003387 }
3388 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003389#if ENABLE_HUSH_FAST
3390 G.count_SIGCHLD++;
3391//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3392#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003393 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003394#if !BB_MMU
3395 free(to_free);
3396#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003397 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003398 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003399 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003400}
3401
Eric Andersen25f27032001-04-26 23:22:31 +00003402/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3403 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003404static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003405{
3406 int openfd, mode;
3407 struct redir_struct *redir;
3408
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003409 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003410 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003411 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003412 if (squirrel && redir->rd_fd < 3
3413 && squirrel[redir->rd_fd] < 0
3414 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003415 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003416 }
3417 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3418 * of the heredoc */
3419 debug_printf_parse("set heredoc '%s'\n",
3420 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003421 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003422 continue;
3423 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003424
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003425 if (redir->rd_dup == REDIRFD_TO_FILE) {
3426 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003427 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003428 if (redir->rd_filename == NULL) {
3429 /* Something went wrong in the parse.
3430 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003431 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003432 continue;
3433 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003434 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003435 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003436 openfd = open_or_warn(p, mode);
3437 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003438 if (openfd < 0) {
3439 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003440 * bash and ash both lose it as well (though zsh doesn't!) */
3441//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003442 return 1;
3443 }
3444 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003445 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003446 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003447 }
3448
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003449 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003450 if (squirrel && redir->rd_fd < 3
3451 && squirrel[redir->rd_fd] < 0
3452 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003453 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003454 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003455 if (openfd == REDIRFD_CLOSE) {
3456 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003457 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003458 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003459 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003460 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003461 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003462 }
Eric Andersen25f27032001-04-26 23:22:31 +00003463 }
3464 }
3465 return 0;
3466}
3467
3468static void restore_redirects(int squirrel[])
3469{
3470 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003471 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003472 fd = squirrel[i];
3473 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003474 /* We simply die on error */
3475 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003476 }
3477 }
3478}
3479
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003480
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003481static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003482
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003483/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003484static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003485{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003486 char **p;
3487 struct command *command;
3488 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003489 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003490
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003491 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003492 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003493 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003494 for (i = 0; i < pi->num_cmds; i++) {
3495 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003496 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003497 if (command->argv) {
3498 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003499 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003500 }
3501 free_strings(command->argv);
3502 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003503 }
3504 /* not "else if": on syntax error, we may have both! */
3505 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003506 debug_printf_clean(" begin group (cmd_type:%d)\n",
3507 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003508 free_pipe_list(command->group);
3509 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003510 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003511 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003512 /* else is crucial here.
3513 * If group != NULL, child_func is meaningless */
3514#if ENABLE_HUSH_FUNCTIONS
3515 else if (command->child_func) {
3516 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3517 command->child_func->parent_cmd = NULL;
3518 }
3519#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003520#if !BB_MMU
3521 free(command->group_as_string);
3522 command->group_as_string = NULL;
3523#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003524 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003525 debug_printf_clean(" redirect %d%s",
3526 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003527 /* guard against the case >$FOO, where foo is unset or blank */
3528 if (r->rd_filename) {
3529 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3530 free(r->rd_filename);
3531 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003532 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003533 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003534 rnext = r->next;
3535 free(r);
3536 }
3537 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003538 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003539 free(pi->cmds); /* children are an array, they get freed all at once */
3540 pi->cmds = NULL;
3541#if ENABLE_HUSH_JOB
3542 free(pi->cmdtext);
3543 pi->cmdtext = NULL;
3544#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003545}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003546
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003547static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003548{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003549 struct pipe *pi, *next;
3550
3551 for (pi = head; pi; pi = next) {
3552#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003553 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003554#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003555 free_pipe(pi);
3556 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003557 next = pi->next;
3558 /*pi->next = NULL;*/
3559 free(pi);
3560 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003561}
3562
3563
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003564static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003565#if BB_MMU
3566#define parse_stream(pstring, input, end_trigger) \
3567 parse_stream(input, end_trigger)
3568#endif
3569static struct pipe *parse_stream(char **pstring,
3570 struct in_str *input,
3571 int end_trigger);
3572static void parse_and_run_string(const char *s);
3573
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003574
Mike Frysinger93cadc22009-05-27 17:06:25 -04003575static char *find_in_path(const char *arg)
3576{
3577 char *ret = NULL;
3578 const char *PATH = get_local_var_value("PATH");
3579
3580 if (!PATH)
3581 return NULL;
3582
3583 while (1) {
3584 const char *end = strchrnul(PATH, ':');
3585 int sz = end - PATH; /* must be int! */
3586
3587 free(ret);
3588 if (sz != 0) {
3589 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3590 } else {
3591 /* We have xxx::yyyy in $PATH,
3592 * it means "use current dir" */
3593 ret = xstrdup(arg);
3594 }
3595 if (access(ret, F_OK) == 0)
3596 break;
3597
3598 if (*end == '\0') {
3599 free(ret);
3600 return NULL;
3601 }
3602 PATH = end + 1;
3603 }
3604
3605 return ret;
3606}
3607
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003608static const struct built_in_command* find_builtin_helper(const char *name,
3609 const struct built_in_command *x,
3610 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003611{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003612 while (x != end) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01003613 if (strcmp(name, x->b_cmd) != 0) {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003614 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003615 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003616 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003617 debug_printf_exec("found builtin '%s'\n", name);
3618 return x;
3619 }
3620 return NULL;
3621}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003622static const struct built_in_command* find_builtin1(const char *name)
3623{
3624 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3625}
3626static const struct built_in_command* find_builtin(const char *name)
3627{
3628 const struct built_in_command *x = find_builtin1(name);
3629 if (x)
3630 return x;
3631 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3632}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003633
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003634#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003635static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003636{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003637 struct function **funcpp = &G.top_func;
3638 while (*funcpp) {
3639 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003640 break;
3641 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003642 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003643 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003644 return funcpp;
3645}
3646
3647static const struct function *find_function(const char *name)
3648{
3649 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003650 if (funcp)
3651 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003652 return funcp;
3653}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003654
Denis Vlasenkobc569742009-04-12 20:35:19 +00003655/* Note: takes ownership on name ptr */
3656static struct function *new_function(char *name)
3657{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003658 struct function **funcpp = find_function_slot(name);
3659 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003660
Denys Vlasenko873273d2009-09-12 14:47:41 +02003661 if (funcp != NULL) {
3662 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003663 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3664 if (!cmd) {
3665 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3666 free(funcp->name);
3667 /* Note: if !funcp->body, do not free body_as_string!
3668 * This is a special case of "-F name body" function:
3669 * body_as_string was not malloced! */
3670 if (funcp->body) {
3671 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003672# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003673 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003674# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003675 }
3676 } else {
3677 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3678 cmd->argv[0] = funcp->name;
3679 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003680# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003681 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003682# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003683 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003684 } else {
3685 debug_printf_exec("remembering new function '%s'\n", name);
3686 funcp = *funcpp = xzalloc(sizeof(*funcp));
3687 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003688 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003689
Denis Vlasenkobc569742009-04-12 20:35:19 +00003690 funcp->name = name;
3691 return funcp;
3692}
3693
Denis Vlasenko40e84372009-04-18 11:23:38 +00003694static void unset_func(const char *name)
3695{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003696 struct function **funcpp = find_function_slot(name);
3697 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003698
Denys Vlasenko873273d2009-09-12 14:47:41 +02003699 if (funcp != NULL) {
3700 debug_printf_exec("freeing function '%s'\n", funcp->name);
3701 *funcpp = funcp->next;
3702 /* funcp is unlinked now, deleting it.
3703 * Note: if !funcp->body, the function was created by
3704 * "-F name body", do not free ->body_as_string
3705 * and ->name as they were not malloced. */
3706 if (funcp->body) {
3707 free_pipe_list(funcp->body);
3708 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003709# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003710 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003711# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003712 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003713 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003714 }
3715}
3716
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003717# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003718#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003719 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003720# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003721static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003722 const struct function *funcp,
3723 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003724static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003725 const struct function *funcp,
3726 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003727{
3728# if BB_MMU
3729 int n = 1;
3730
3731 argv[0] = G.global_argv[0];
3732 G.global_argv = argv;
3733 while (*++argv)
3734 n++;
3735 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003736 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003737 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003738 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003739 _exit(n);
3740# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003741 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003742 funcp->body_as_string,
3743 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003744 argv + 1,
3745 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003746# endif
3747}
3748
3749static int run_function(const struct function *funcp, char **argv)
3750{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003751 int rc;
3752 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003753 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003754
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003755 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003756
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003757 /* "we are in function, ok to use return" */
3758 sv_flg = G.flag_return_in_progress;
3759 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003760# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003761 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003762# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003763
Denis Vlasenkobc569742009-04-12 20:35:19 +00003764 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003765# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003766 if (!funcp->body) {
3767 /* Function defined by -F */
3768 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003769 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003770 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003771# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003772 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003773 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003774 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003775
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003776# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003777 {
3778 struct variable *var;
3779 struct variable **var_pp;
3780
3781 var_pp = &G.top_var;
3782 while ((var = *var_pp) != NULL) {
3783 if (var->func_nest_level < G.func_nest_level) {
3784 var_pp = &var->next;
3785 continue;
3786 }
3787 /* Unexport */
3788 if (var->flg_export)
3789 bb_unsetenv(var->varstr);
3790 /* Remove from global list */
3791 *var_pp = var->next;
3792 /* Free */
3793 if (!var->max_len)
3794 free(var->varstr);
3795 free(var);
3796 }
3797 G.func_nest_level--;
3798 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003799# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003800 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003801
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003802 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003803
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003804 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003805}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003806#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003807
3808
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003809#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003810#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003811 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003812#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003813#define exec_builtin(to_free, x, argv) \
3814 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003815#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003816static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003817 const struct built_in_command *x,
3818 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003819static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003820 const struct built_in_command *x,
3821 char **argv)
3822{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003823#if BB_MMU
Denys Vlasenko17323a62010-01-28 01:57:05 +01003824 int rcode = x->b_function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003825 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003826 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003827#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003828 /* On NOMMU, we must never block!
3829 * Example: { sleep 99 | read line; } & echo Ok
3830 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003831 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003832 argv[0],
3833 G.global_argv[0],
3834 G.global_argv + 1,
3835 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003836#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003837}
3838
3839
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003840static void execvp_or_die(char **argv) NORETURN;
3841static void execvp_or_die(char **argv)
3842{
3843 debug_printf_exec("execing '%s'\n", argv[0]);
3844 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3845 execvp(argv[0], argv);
3846 bb_perror_msg("can't execute '%s'", argv[0]);
3847 _exit(127); /* bash compat */
3848}
3849
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003850#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003851static void dump_cmd_in_x_mode(char **argv)
3852{
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003853 if (G_x_mode && argv) {
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003854 /* We want to output the line in one write op */
3855 char *buf, *p;
3856 int len;
3857 int n;
3858
3859 len = 3;
3860 n = 0;
3861 while (argv[n])
3862 len += strlen(argv[n++]) + 1;
3863 buf = xmalloc(len);
3864 buf[0] = '+';
3865 p = buf + 1;
3866 n = 0;
3867 while (argv[n])
3868 p += sprintf(p, " %s", argv[n++]);
3869 *p++ = '\n';
3870 *p = '\0';
3871 fputs(buf, stderr);
3872 free(buf);
3873 }
3874}
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003875#else
3876# define dump_cmd_in_x_mode(argv) ((void)0)
3877#endif
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003878
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003879#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003880#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3881 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3882#define pseudo_exec(nommu_save, command, argv_expanded) \
3883 pseudo_exec(command, argv_expanded)
3884#endif
3885
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003886/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003887 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003888 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003889 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003890 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003891static void pseudo_exec_argv(nommu_save_t *nommu_save,
3892 char **argv, int assignment_cnt,
3893 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003894static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003895 char **argv, int assignment_cnt,
3896 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003897{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003898 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003899
Denis Vlasenko9504e442008-10-29 01:19:15 +00003900 new_env = expand_assignments(argv, assignment_cnt);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003901 dump_cmd_in_x_mode(new_env);
Denys Vlasenko889550b2010-07-14 19:01:25 +02003902
3903 if (!argv[assignment_cnt]) {
3904 /* Case when we are here: ... | var=val | ...
3905 * (note that we do not exit early, i.e., do not optimize out
3906 * expand_assignments(): think about ... | var=`sleep 1` | ...
3907 */
3908 free_strings(new_env);
3909 _exit(EXIT_SUCCESS);
3910 }
3911
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003912#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003913 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003914 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003915 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003916 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003917#else
3918 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003919 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003920#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02003921
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003922 if (argv_expanded) {
3923 argv = argv_expanded;
3924 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003925 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003926#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003927 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003928#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003929 }
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003930 dump_cmd_in_x_mode(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003931
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003932#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3933 if (strchr(argv[0], '/') != NULL)
3934 goto skip;
3935#endif
3936
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003937 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003938 * Depending on context, this might be redundant. But it's
3939 * easier to waste a few CPU cycles than it is to figure out
3940 * if this is one of those cases.
3941 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003942 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003943 /* On NOMMU, it is more expensive to re-execute shell
3944 * just in order to run echo or test builtin.
3945 * It's better to skip it here and run corresponding
3946 * non-builtin later. */
3947 const struct built_in_command *x;
3948 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003949 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003950 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003951 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003952 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003953#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003954 /* Check if the command matches any functions */
3955 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003956 const struct function *funcp = find_function(argv[0]);
3957 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003958 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003959 }
3960 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003961#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003962
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003963#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003964 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003965 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003966 int a = find_applet_by_name(argv[0]);
3967 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003968# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003969 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003970 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003971 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003972 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003973# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003974 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003975 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003976 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3977 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003978 /* If they called chroot or otherwise made the binary no longer
3979 * executable, fall through */
3980 }
3981 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003982#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003983
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003984#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003985 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003986#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003987 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003988}
3989
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003990/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003991 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003992static void pseudo_exec(nommu_save_t *nommu_save,
3993 struct command *command,
3994 char **argv_expanded) NORETURN;
3995static void pseudo_exec(nommu_save_t *nommu_save,
3996 struct command *command,
3997 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003998{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003999 if (command->argv) {
4000 pseudo_exec_argv(nommu_save, command->argv,
4001 command->assignment_cnt, argv_expanded);
4002 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004003
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004004 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00004005 /* Cases when we are here:
4006 * ( list )
4007 * { list } &
4008 * ... | ( list ) | ...
4009 * ... | { list } | ...
4010 */
4011#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00004012 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004013 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004014 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004015 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00004016 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004017 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00004018 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004019#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004020 re_execute_shell(&nommu_save->argv_from_re_execing,
4021 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004022 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02004023 G.global_argv + 1,
4024 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00004025#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004026 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004027
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004028 /* Case when we are here: ... | >file */
4029 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004030 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00004031}
4032
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004033#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004034static const char *get_cmdtext(struct pipe *pi)
4035{
4036 char **argv;
4037 char *p;
4038 int len;
4039
4040 /* This is subtle. ->cmdtext is created only on first backgrounding.
4041 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004042 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004043 if (pi->cmdtext)
4044 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004045 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004046 if (!argv || !argv[0]) {
4047 pi->cmdtext = xzalloc(1);
4048 return pi->cmdtext;
4049 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004050
4051 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004052 do {
4053 len += strlen(*argv) + 1;
4054 } while (*++argv);
4055 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004056 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004057 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004058 do {
4059 len = strlen(*argv);
4060 memcpy(p, *argv, len);
4061 p += len;
4062 *p++ = ' ';
4063 } while (*++argv);
4064 p[-1] = '\0';
4065 return pi->cmdtext;
4066}
4067
Eric Andersenbafd94f2001-05-02 16:11:59 +00004068static void insert_bg_job(struct pipe *pi)
4069{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004070 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004071 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004072
4073 /* Linear search for the ID of the job to use */
4074 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004075 for (job = G.job_list; job; job = job->next)
4076 if (job->jobid >= pi->jobid)
4077 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004078
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004079 /* Add job to the list of running jobs */
4080 jobp = &G.job_list;
4081 while ((job = *jobp) != NULL)
4082 jobp = &job->next;
4083 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00004084
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004085 *job = *pi; /* physical copy */
4086 job->next = NULL;
4087 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4088 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004089 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004090 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004091 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004092 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004093 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00004094
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004095 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004096 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
4097 /* Last command's pid goes to $! */
4098 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
4099 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004100}
4101
Eric Andersenbafd94f2001-05-02 16:11:59 +00004102static void remove_bg_job(struct pipe *pi)
4103{
4104 struct pipe *prev_pipe;
4105
Denis Vlasenko87a86552008-07-29 19:43:10 +00004106 if (pi == G.job_list) {
4107 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004108 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004109 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004110 while (prev_pipe->next != pi)
4111 prev_pipe = prev_pipe->next;
4112 prev_pipe->next = pi->next;
4113 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004114 if (G.job_list)
4115 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00004116 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00004117 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00004118}
Eric Andersen028b65b2001-06-28 01:10:11 +00004119
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004120/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00004121static void delete_finished_bg_job(struct pipe *pi)
4122{
4123 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004124 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004125 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004126 free(pi);
4127}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004128#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004129
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004130/* Check to see if any processes have exited -- if they
4131 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00004132static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00004133{
Eric Andersenc798b072001-06-22 06:23:03 +00004134 int attributes;
4135 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004136#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00004137 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004138#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00004139 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004140 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004141
Denis Vlasenkod5762932009-03-31 11:22:57 +00004142 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4143
Eric Andersenc798b072001-06-22 06:23:03 +00004144 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004145 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00004146 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00004147
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004148 errno = 0;
4149#if ENABLE_HUSH_FAST
4150 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4151//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4152//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02004153 /* There was neither fork nor SIGCHLD since last waitpid */
4154 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004155 if (!G.we_have_children) {
4156 errno = ECHILD;
4157 return -1;
4158 }
4159 if (fg_pipe == NULL) { /* is WNOHANG set? */
4160 /* We have children, but they did not exit
4161 * or stop yet (we saw no SIGCHLD) */
4162 return 0;
4163 }
4164 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4165 }
4166#endif
4167
Denis Vlasenko1359da62007-04-21 23:27:30 +00004168/* Do we do this right?
4169 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004170 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00004171 * [3]+ Stopped sleep 20 | false
4172 * bash-3.00# echo $?
4173 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004174 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00004175 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004176 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004177 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004178 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004179 int dead;
4180
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004181#if ENABLE_HUSH_FAST
4182 i = G.count_SIGCHLD;
4183#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004184 childpid = waitpid(-1, &status, attributes);
4185 if (childpid <= 0) {
4186 if (childpid && errno != ECHILD)
4187 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004188#if ENABLE_HUSH_FAST
4189 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004190 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004191 G.handled_SIGCHLD = i;
4192//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4193 }
4194#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004195 break;
4196 }
4197 dead = WIFEXITED(status) || WIFSIGNALED(status);
4198
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00004199#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00004200 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004201 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004202 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4203 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004204 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004205 childpid, WTERMSIG(status), WEXITSTATUS(status));
4206 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004207 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004208 childpid, WEXITSTATUS(status));
4209#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004210 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00004211 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004212 for (i = 0; i < fg_pipe->num_cmds; i++) {
4213 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4214 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004215 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004216 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004217 fg_pipe->cmds[i].pid = 0;
4218 fg_pipe->alive_cmds--;
4219 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004220 /* last process gives overall exitstatus */
4221 rcode = WEXITSTATUS(status);
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004222 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00004223 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004224 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00004225 */
4226 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00004227 int sig = WTERMSIG(status);
4228 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004229 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4230 * Maybe we need to use sig | 128? */
4231 rcode = sig + 128;
Denis Vlasenko40e84372009-04-18 11:23:38 +00004232 }
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004233 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00004234 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004235 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004236 fg_pipe->cmds[i].is_stopped = 1;
4237 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00004238 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004239 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4240 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4241 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004242 /* All processes in fg pipe have exited or stopped */
4243/* Note: *non-interactive* bash does not continue if all processes in fg pipe
4244 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4245 * and "killall -STOP cat" */
4246 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004247#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004248 if (fg_pipe->alive_cmds)
4249 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004250#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004251 return rcode;
4252 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02004253 if (!fg_pipe->alive_cmds)
4254 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004255 }
4256 /* There are still running processes in the fg pipe */
4257 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00004258 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004259 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00004260 }
4261
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004262#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004263 /* We asked to wait for bg or orphaned children */
4264 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004265 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004266 for (i = 0; i < pi->num_cmds; i++) {
4267 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004268 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00004269 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00004270 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004271 /* Happens when shell is used as init process (init=/bin/sh) */
4272 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004273 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00004274
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004275 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00004276 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00004277 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004278 pi->cmds[i].pid = 0;
4279 pi->alive_cmds--;
4280 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004281 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00004282 printf(JOB_STATUS_FORMAT, pi->jobid,
4283 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004284 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004285 }
4286 } else {
4287 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004288 pi->cmds[i].is_stopped = 1;
4289 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004290 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004291#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004292 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004293
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004294 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00004295}
4296
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004297#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00004298static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4299{
4300 pid_t p;
4301 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04004302 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004303 /* Job finished, move the shell to the foreground */
4304 p = getpgrp(); /* our process group id */
4305 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4306 tcsetpgrp(G_interactive_fd, p);
4307 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00004308 return rcode;
4309}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004310#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00004311
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004312/* Start all the jobs, but don't wait for anything to finish.
4313 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00004314 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00004315 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00004316 * to finish to determine the exit status of the pipe. If the pipe
4317 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00004318 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00004319 * return value.
4320 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00004321 * Returns -1 only if started some children. IOW: we have to
4322 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00004323 *
4324 * The only case when we do not need to [v]fork is when the pipe
4325 * is single, non-backgrounded, non-subshell command. Examples:
4326 * cmd ; ... { list } ; ...
4327 * cmd && ... { list } && ...
4328 * cmd || ... { list } || ...
4329 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4330 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004331 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00004332 *
4333 * Cases when we must fork:
4334 * non-single: cmd | cmd
4335 * backgrounded: cmd & { list } &
4336 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00004337 */
Denys Vlasenko29082232010-07-16 13:52:32 +02004338#if !ENABLE_HUSH_MODE_X
4339#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
4340 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
4341#endif
4342static int redirect_and_varexp_helper(char ***new_env_p, struct variable **old_vars_p, struct command *command, int squirrel[3], char **argv_expanded)
4343{
4344 /* setup_redirects acts on file descriptors, not FILEs.
4345 * This is perfect for work that comes after exec().
4346 * Is it really safe for inline use? Experimentally,
4347 * things seem to work. */
4348 int rcode = setup_redirects(command, squirrel);
4349 if (rcode == 0) {
4350 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
4351 *new_env_p = new_env;
4352 dump_cmd_in_x_mode(new_env);
4353 dump_cmd_in_x_mode(argv_expanded);
4354 if (old_vars_p)
4355 *old_vars_p = set_vars_and_save_old(new_env);
4356 }
4357 return rcode;
4358}
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02004359static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004360{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004361 static const char *const null_ptr = NULL;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004362
4363 int cmd_no;
4364 int next_infd;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004365 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004366 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004367 char **argv;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004368 /* it is not always needed, but we aim to smaller code */
4369 int squirrel[] = { -1, -1, -1 };
4370 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004371
Denis Vlasenko552433b2009-04-04 19:29:21 +00004372 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004373 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004374
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004375 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004376 pi->stopped_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004377 command = &pi->cmds[0];
Denis Vlasenko552433b2009-04-04 19:29:21 +00004378 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004379
Denis Vlasenko552433b2009-04-04 19:29:21 +00004380 if (pi->num_cmds != 1
4381 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004382 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00004383 ) {
4384 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004385 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004386
Denis Vlasenko552433b2009-04-04 19:29:21 +00004387 pi->alive_cmds = 1;
4388
4389 debug_printf_exec(": group:%p argv:'%s'\n",
4390 command->group, command->argv ? command->argv[0] : "NONE");
4391
4392 if (command->group) {
4393#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004394 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004395 /* "executing" func () { list } */
4396 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004397
Denis Vlasenkobc569742009-04-12 20:35:19 +00004398 funcp = new_function(command->argv[0]);
4399 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004400 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004401# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004402 funcp->body_as_string = command->group_as_string;
4403 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004404# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004405 command->group = NULL;
4406 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00004407 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4408 funcp->parent_cmd = command;
4409 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004410
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004411 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4412 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00004413 return EXIT_SUCCESS;
4414 }
4415#endif
4416 /* { list } */
4417 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004418 rcode = 1; /* exitcode if redir failed */
4419 if (setup_redirects(command, squirrel) == 0) {
4420 debug_printf_exec(": run_list\n");
4421 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004422 }
Eric Andersen04407e52001-06-07 16:42:05 +00004423 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004424 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004425 debug_leave();
4426 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004427 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004428 }
4429
Denis Vlasenko552433b2009-04-04 19:29:21 +00004430 argv = command->argv ? command->argv : (char **) &null_ptr;
4431 {
4432 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004433#if ENABLE_HUSH_FUNCTIONS
4434 const struct function *funcp;
4435#else
4436 enum { funcp = 0 };
4437#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004438 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004439 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004440
Denis Vlasenko552433b2009-04-04 19:29:21 +00004441 if (argv[command->assignment_cnt] == NULL) {
4442 /* Assignments, but no command */
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004443 /* Ensure redirects take effect (that is, create files).
Denys Vlasenko29082232010-07-16 13:52:32 +02004444 * Try "a=t >file" */
4445#if 0 /* A few cases in testsuite fail with this code. FIXME */
4446 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
4447 /* Set shell variables */
4448 if (new_env) {
4449 argv = new_env;
4450 while (*argv) {
4451 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4452 /* Do we need to flag set_local_var() errors?
4453 * "assignment to readonly var" and "putenv error"
4454 */
4455 argv++;
4456 }
4457 }
4458 /* Redirect error sets $? to 1. Otherwise,
4459 * if evaluating assignment value set $?, retain it.
4460 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4461 if (rcode == 0)
4462 rcode = G.last_exitcode;
4463 /* Exit, _skipping_ variable restoring code: */
4464 goto clean_up_and_ret0;
4465
4466#else /* Older, bigger, but more correct code */
4467
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004468 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004469 restore_redirects(squirrel);
4470 /* Set shell variables */
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004471 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004472 bb_putchar_stderr('+');
Denis Vlasenko552433b2009-04-04 19:29:21 +00004473 while (*argv) {
Denys Vlasenko29082232010-07-16 13:52:32 +02004474 char *p = expand_string_to_string(*argv);
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004475 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004476 fprintf(stderr, " %s", p);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004477 debug_printf_exec("set shell var:'%s'->'%s'\n",
4478 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004479 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenko29082232010-07-16 13:52:32 +02004480 /* Do we need to flag set_local_var() errors?
4481 * "assignment to readonly var" and "putenv error"
4482 */
Denis Vlasenko552433b2009-04-04 19:29:21 +00004483 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004484 }
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004485 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004486 bb_putchar_stderr('\n');
Denys Vlasenkob3389de2010-07-15 12:33:37 +02004487 /* Redirect error sets $? to 1. Otherwise,
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004488 * if evaluating assignment value set $?, retain it.
4489 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4490 if (rcode == 0)
4491 rcode = G.last_exitcode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004492 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004493 debug_leave();
4494 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004495 return rcode;
Denys Vlasenko29082232010-07-16 13:52:32 +02004496#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00004497 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004498
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004499 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004500 if (0) {}
4501#if ENABLE_HUSH_BASH_COMPAT
4502 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004503 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4504 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004505#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004506#ifdef CMD_SINGLEWORD_NOGLOB_COND
4507 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4508 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4509
4510 }
4511#endif
4512 else {
4513 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4514 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004515
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004516 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004517 if (!argv_expanded[0]) {
Denys Vlasenko385cc592010-01-12 06:47:39 +01004518 free(argv_expanded);
Mike Frysinger28736c32009-10-18 01:11:45 -04004519 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004520 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004521 }
4522
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004523 x = find_builtin(argv_expanded[0]);
4524#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004525 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004526 if (!x)
4527 funcp = find_function(argv_expanded[0]);
4528#endif
4529 if (x || funcp) {
4530 if (!funcp) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01004531 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004532 debug_printf("exec with redirects only\n");
4533 rcode = setup_redirects(command, NULL);
4534 goto clean_up_and_ret1;
4535 }
Eric Andersen25f27032001-04-26 23:22:31 +00004536 }
Denys Vlasenko29082232010-07-16 13:52:32 +02004537 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004538 if (rcode == 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004539 if (!funcp) {
4540 debug_printf_exec(": builtin '%s' '%s'...\n",
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004541 x->b_cmd, argv_expanded[1]);
Denys Vlasenko17323a62010-01-28 01:57:05 +01004542 rcode = x->b_function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004543 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004544 }
4545#if ENABLE_HUSH_FUNCTIONS
4546 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004547# if ENABLE_HUSH_LOCAL
4548 struct variable **sv;
4549 sv = G.shadowed_vars_pp;
4550 G.shadowed_vars_pp = &old_vars;
4551# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004552 debug_printf_exec(": function '%s' '%s'...\n",
4553 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004554 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004555# if ENABLE_HUSH_LOCAL
4556 G.shadowed_vars_pp = sv;
4557# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004558 }
4559#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004560 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004561 clean_up_and_ret:
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004562 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004563 add_vars(old_vars);
Denys Vlasenko29082232010-07-16 13:52:32 +02004564/* clean_up_and_ret0: */
4565 restore_redirects(squirrel);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004566 clean_up_and_ret1:
4567 free(argv_expanded);
4568 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004569 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004570 debug_printf_exec("run_pipe return %d\n", rcode);
4571 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004572 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004573
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004574 if (ENABLE_FEATURE_SH_STANDALONE) {
4575 int n = find_applet_by_name(argv_expanded[0]);
4576 if (n >= 0 && APPLET_IS_NOFORK(n)) {
Denys Vlasenko29082232010-07-16 13:52:32 +02004577 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004578 if (rcode == 0) {
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004579 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4580 argv_expanded[0], argv_expanded[1]);
4581 rcode = run_nofork_applet(n, argv_expanded);
4582 }
4583 goto clean_up_and_ret;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004584 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004585 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00004586 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004587 }
4588
Denis Vlasenko552433b2009-04-04 19:29:21 +00004589 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004590 /* NB: argv_expanded may already be created, and that
4591 * might include `cmd` runs! Do not rerun it! We *must*
4592 * use argv_expanded if it's non-NULL */
4593
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004594 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004595 pi->alive_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004596 next_infd = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004597
Denys Vlasenko889550b2010-07-14 19:01:25 +02004598 cmd_no = 0;
4599 while (cmd_no < pi->num_cmds) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004600 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004601#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004602 volatile nommu_save_t nommu_save;
4603 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004604 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004605 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004606 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004607#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02004608 command = &pi->cmds[cmd_no];
4609 cmd_no++;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004610 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004611 debug_printf_exec(": pipe member '%s' '%s'...\n",
4612 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004613 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004614 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004615 }
Eric Andersen25f27032001-04-26 23:22:31 +00004616
4617 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004618 pipefds.rd = 0;
4619 pipefds.wr = 1;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004620 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004621 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004622
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004623 command->pid = BB_MMU ? fork() : vfork();
4624 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004625#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004626 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004627 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004628
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004629 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004630 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004631 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004632 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004633 pgrp = pi->pgrp;
4634 if (pgrp < 0) /* true for 1st process only */
4635 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004636 if (setpgid(0, pgrp) == 0
4637 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004638 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004639 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004640 /* We do it in *every* child, not just first,
4641 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004642 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004643 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004644 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004645#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004646 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4647 /* 1st cmd in backgrounded pipe
4648 * should have its stdin /dev/null'ed */
4649 close(0);
4650 if (open(bb_dev_null, O_RDONLY))
4651 xopen("/", O_RDONLY);
4652 } else {
Denys Vlasenko889550b2010-07-14 19:01:25 +02004653 xmove_fd(next_infd, 0);
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004654 }
4655 xmove_fd(pipefds.wr, 1);
4656 if (pipefds.rd > 1)
4657 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004658 /* Like bash, explicit redirects override pipes,
4659 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004660 if (setup_redirects(command, NULL))
4661 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004662
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004663 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004664 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4665
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004666 /* Stores to nommu_save list of env vars putenv'ed
4667 * (NOMMU, on MMU we don't need that) */
4668 /* cast away volatility... */
4669 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004670 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004671 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004672
Denis Vlasenkof9375282009-04-05 19:13:39 +00004673 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004674#if ENABLE_HUSH_FAST
4675 G.count_SIGCHLD++;
4676//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4677#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004678 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004679#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004680 /* Clean up after vforked child */
4681 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004682 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004683 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004684 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004685#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004686 free(argv_expanded);
4687 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004688 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004689 /* Clearly indicate, was it fork or vfork */
Pascal Bellard926031b2010-07-04 15:32:38 +02004690 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004691 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004692 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004693#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004694 /* Second and next children need to know pid of first one */
4695 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004696 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004697#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004698 }
Eric Andersen25f27032001-04-26 23:22:31 +00004699
Denys Vlasenko889550b2010-07-14 19:01:25 +02004700 if (cmd_no > 1)
4701 close(next_infd);
4702 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004703 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004704 /* Pass read (output) pipe end to next iteration */
Denys Vlasenko889550b2010-07-14 19:01:25 +02004705 next_infd = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004706 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004707
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004708 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004709 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004710 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4711 return 1;
4712 }
4713
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004714 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004715 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004716 return -1;
4717}
4718
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004719#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004720static void debug_print_tree(struct pipe *pi, int lvl)
4721{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004722 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004723 [PIPE_SEQ] = "SEQ",
4724 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004725 [PIPE_OR ] = "OR" ,
4726 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004727 };
4728 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004729 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004730# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004731 [RES_IF ] = "IF" ,
4732 [RES_THEN ] = "THEN" ,
4733 [RES_ELIF ] = "ELIF" ,
4734 [RES_ELSE ] = "ELSE" ,
4735 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004736# endif
4737# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004738 [RES_FOR ] = "FOR" ,
4739 [RES_WHILE] = "WHILE",
4740 [RES_UNTIL] = "UNTIL",
4741 [RES_DO ] = "DO" ,
4742 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004743# endif
4744# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004745 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004746# endif
4747# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004748 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004749 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004750 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004751 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004752 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004753# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004754 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004755 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004756 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004757 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004758 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004759 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004760 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004761# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004762 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004763# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004764 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004765
4766 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004767
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004768 pin = 0;
4769 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004770 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4771 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004772 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004773 while (prn < pi->num_cmds) {
4774 struct command *command = &pi->cmds[prn];
4775 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004776
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004777 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004778 lvl*2, "", prn,
4779 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004780 if (command->group) {
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004781 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004782 CMDTYPE[command->cmd_type],
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004783 argv
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004784# if !BB_MMU
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004785 , " group_as_string:", command->group_as_string
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004786# else
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004787 , "", ""
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004788# endif
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004789 );
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004790 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004791 prn++;
4792 continue;
4793 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004794 if (argv) while (*argv) {
4795 fprintf(stderr, " '%s'", *argv);
4796 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004797 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004798 fprintf(stderr, "\n");
4799 prn++;
4800 }
4801 pi = pi->next;
4802 pin++;
4803 }
4804}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004805#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004806
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004807/* NB: called by pseudo_exec, and therefore must not modify any
4808 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004809static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004810{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004811#if ENABLE_HUSH_CASE
4812 char *case_word = NULL;
4813#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004814#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004815 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004816 char **for_lcur = NULL;
4817 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004818#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004819 smallint last_followup;
4820 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004821#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004822 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004823#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004824 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004825#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004826#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004827 smallint rword; /* enum reserved_style */
4828 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004829#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004830
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004831 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004832 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004833
Denis Vlasenko06810332007-05-21 23:30:54 +00004834#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004835 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004836 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4837 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004838 continue;
4839 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004840 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004841 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004842 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004843 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004844 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004845 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004846 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004847 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004848 continue;
4849 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004850 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4851 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004852 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004853 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004854 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004855 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004856 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004857 }
4858 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004859#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004860
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004861 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004862 * in order to return, no direct "return" statements please.
4863 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004864
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004865#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004866 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004867#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004868
Denis Vlasenko0e151382009-04-06 18:40:31 +00004869#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004870 rword = RES_NONE;
4871 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004872#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004873 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004874 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004875
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004876 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004877 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004878 if (G.flag_SIGINT)
4879 break;
4880
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004881 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004882 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4883 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004884#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004885 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004886 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004887 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004888 /* start of a loop: remember where loop starts */
4889 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004890 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004891 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004892#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004893 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004894 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004895 if ((rcode == 0 && last_followup == PIPE_OR)
4896 || (rcode != 0 && last_followup == PIPE_AND)
4897 ) {
4898 /* It is "<true> || CMD" or "<false> && CMD"
4899 * and we should not execute CMD */
4900 debug_printf_exec("skipped cmd because of || or &&\n");
4901 last_followup = pi->followup;
4902 continue;
4903 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004904 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004905 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004906 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004907#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004908 if (cond_code) {
4909 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004910 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004911 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004912 /* "if <false> THEN cmd": skip cmd */
4913 continue;
4914 }
4915 } else {
4916 if (rword == RES_ELSE || rword == RES_ELIF) {
4917 /* "if <true> then ... ELSE/ELIF cmd":
4918 * skip cmd and all following ones */
4919 break;
4920 }
4921 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004922#endif
4923#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004924 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004925 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004926 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004927
4928 static const char encoded_dollar_at[] ALIGN1 = {
4929 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4930 }; /* encoded representation of "$@" */
4931 static const char *const encoded_dollar_at_argv[] = {
4932 encoded_dollar_at, NULL
4933 }; /* argv list with one element: "$@" */
4934 char **vals;
4935
4936 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004937 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004938 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004939 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004940 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004941 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004942 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004943 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004944 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004945 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004946 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004947 debug_print_strings("for_list made from", vals);
4948 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004949 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004950 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004951 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004952 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004953 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004954 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004955 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004956 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004957 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004958 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004959 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004960 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004961 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 +02004962 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004963 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004964 if (rword == RES_IN) {
4965 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4966 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004967 if (rword == RES_DONE) {
4968 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004969 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004970#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004971#if ENABLE_HUSH_CASE
4972 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004973 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004974 continue;
4975 }
4976 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004977 char **argv;
4978
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004979 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4980 break;
4981 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004982 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004983 while (*argv) {
4984 char *pattern = expand_string_to_string(*argv);
4985 /* TODO: which FNM_xxx flags to use? */
4986 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4987 free(pattern);
4988 if (cond_code == 0) { /* match! we will execute this branch */
4989 free(case_word); /* make future "word)" stop */
4990 case_word = NULL;
4991 break;
4992 }
4993 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004994 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004995 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004996 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004997 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004998 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004999 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005000 }
5001#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00005002 /* Just pressing <enter> in shell should check for jobs.
5003 * OTOH, in non-interactive shell this is useless
5004 * and only leads to extra job checks */
5005 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005006 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00005007 goto check_jobs_and_continue;
5008 continue;
5009 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005010
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005011 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00005012 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005013 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005014 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005015 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005016 {
5017 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005018#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00005019 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005020#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005021 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
5022 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005023 /* We ran a builtin, function, or group.
5024 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005025 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005026 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005027 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005028 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005029#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005030 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005031 if (G.flag_break_continue) {
5032 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005033 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005034 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005035 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00005036 G.depth_break_continue--;
5037 if (G.depth_break_continue == 0)
5038 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005039 /* else: e.g. "continue 2" should *break* once, *then* continue */
5040 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005041 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005042 goto check_jobs_and_break;
5043 /* "continue": simulate end of loop */
5044 rword = RES_DONE;
5045 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005046 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005047#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005048#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02005049 if (G.flag_return_in_progress == 1) {
5050 /* same as "goto check_jobs_and_break" */
5051 checkjobs(NULL);
5052 break;
5053 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005054#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005055 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005056 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005057 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005058 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5059 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005060 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005061#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00005062 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005063 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00005064#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005065 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005066 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005067 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005068#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005069 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005070 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005071 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005072 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005073 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005074 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005075#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005076 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005077 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005078 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005079 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005080 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005081 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00005082 }
5083 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005084
5085 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00005086#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00005087 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005088 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00005089#endif
5090#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005091 /* Beware of "while false; true; do ..."! */
5092 if (pi->next && pi->next->res_word == RES_DO) {
5093 if (rword == RES_WHILE) {
5094 if (rcode) {
5095 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005096 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005097 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5098 goto check_jobs_and_break;
5099 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00005100 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005101 if (rword == RES_UNTIL) {
5102 if (!rcode) {
5103 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005104 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005105 checkjobs(NULL);
5106 break;
5107 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005108 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005109 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005110#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00005111
5112 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00005113 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005114 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00005115
5116#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00005117 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00005118#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00005119#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005120 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00005121 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00005122 free(for_list);
5123#endif
5124#if ENABLE_HUSH_CASE
5125 free(case_word);
5126#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005127 debug_leave();
5128 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00005129 return rcode;
5130}
5131
Eric Andersen25f27032001-04-26 23:22:31 +00005132/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00005133static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00005134{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005135 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00005136 debug_printf_exec("run_and_free_list entered\n");
Denys Vlasenko202a2d12010-07-16 12:36:14 +02005137 if (!G.n_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005138 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00005139 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005140 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005141 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00005142 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00005143 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005144 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00005145 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00005146 return rcode;
5147}
5148
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005149
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00005150static struct pipe *new_pipe(void)
5151{
Eric Andersen25f27032001-04-26 23:22:31 +00005152 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00005153 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005154 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005155 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00005156 return pi;
5157}
5158
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005159/* Command (member of a pipe) is complete, or we start a new pipe
5160 * if ctx->command is NULL.
5161 * No errors possible here.
5162 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005163static int done_command(struct parse_context *ctx)
5164{
5165 /* The command is really already in the pipe structure, so
5166 * advance the pipe counter and make a new, null command. */
5167 struct pipe *pi = ctx->pipe;
5168 struct command *command = ctx->command;
5169
5170 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005171 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005172 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005173 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005174 }
5175 pi->num_cmds++;
5176 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005177 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005178 } else {
5179 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5180 }
5181
5182 /* Only real trickiness here is that the uncommitted
5183 * command structure is not counted in pi->num_cmds. */
5184 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005185 ctx->command = command = &pi->cmds[pi->num_cmds];
5186 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005187 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005188 return pi->num_cmds; /* used only for 0/nonzero check */
5189}
5190
5191static void done_pipe(struct parse_context *ctx, pipe_style type)
5192{
5193 int not_null;
5194
5195 debug_printf_parse("done_pipe entered, followup %d\n", type);
5196 /* Close previous command */
5197 not_null = done_command(ctx);
5198 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005199#if HAS_KEYWORDS
5200 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5201 ctx->ctx_inverted = 0;
5202 ctx->pipe->res_word = ctx->ctx_res_w;
5203#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005204
5205 /* Without this check, even just <enter> on command line generates
5206 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005207 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005208 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00005209#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005210 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00005211#endif
5212#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005213 || ctx->ctx_res_w == RES_DONE
5214 || ctx->ctx_res_w == RES_FOR
5215 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00005216#endif
5217#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005218 || ctx->ctx_res_w == RES_ESAC
5219#endif
5220 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005221 struct pipe *new_p;
5222 debug_printf_parse("done_pipe: adding new pipe: "
5223 "not_null:%d ctx->ctx_res_w:%d\n",
5224 not_null, ctx->ctx_res_w);
5225 new_p = new_pipe();
5226 ctx->pipe->next = new_p;
5227 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005228 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005229 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005230 * This is used to control execution.
5231 * RES_FOR and RES_IN are NOT sticky (needed to support
5232 * cases where variable or value happens to match a keyword):
5233 */
5234#if ENABLE_HUSH_LOOPS
5235 if (ctx->ctx_res_w == RES_FOR
5236 || ctx->ctx_res_w == RES_IN)
5237 ctx->ctx_res_w = RES_NONE;
5238#endif
5239#if ENABLE_HUSH_CASE
5240 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005241 ctx->ctx_res_w = RES_CASE_BODY;
5242 if (ctx->ctx_res_w == RES_CASE)
5243 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005244#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005245 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005246 /* Create the memory for command, roughly:
5247 * ctx->pipe->cmds = new struct command;
5248 * ctx->command = &ctx->pipe->cmds[0];
5249 */
5250 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005251 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005252 }
5253 debug_printf_parse("done_pipe return\n");
5254}
5255
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005256static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005257{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005258 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00005259 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005260 /* Create the memory for command, roughly:
5261 * ctx->pipe->cmds = new struct command;
5262 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005263 */
5264 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005265}
5266
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005267/* If a reserved word is found and processed, parse context is modified
5268 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00005269 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005270#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005271struct reserved_combo {
5272 char literal[6];
5273 unsigned char res;
5274 unsigned char assignment_flag;
5275 int flag;
5276};
5277enum {
5278 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005279# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005280 FLAG_IF = (1 << RES_IF ),
5281 FLAG_THEN = (1 << RES_THEN ),
5282 FLAG_ELIF = (1 << RES_ELIF ),
5283 FLAG_ELSE = (1 << RES_ELSE ),
5284 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005285# endif
5286# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005287 FLAG_FOR = (1 << RES_FOR ),
5288 FLAG_WHILE = (1 << RES_WHILE),
5289 FLAG_UNTIL = (1 << RES_UNTIL),
5290 FLAG_DO = (1 << RES_DO ),
5291 FLAG_DONE = (1 << RES_DONE ),
5292 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005293# endif
5294# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005295 FLAG_MATCH = (1 << RES_MATCH),
5296 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005297# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005298 FLAG_START = (1 << RES_XXXX ),
5299};
5300
5301static const struct reserved_combo* match_reserved_word(o_string *word)
5302{
Eric Andersen25f27032001-04-26 23:22:31 +00005303 /* Mostly a list of accepted follow-up reserved words.
5304 * FLAG_END means we are done with the sequence, and are ready
5305 * to turn the compound list into a command.
5306 * FLAG_START means the word must start a new compound list.
5307 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005308 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005309# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005310 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5311 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5312 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5313 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5314 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5315 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005316# endif
5317# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005318 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5319 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5320 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5321 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5322 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5323 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005324# endif
5325# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005326 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5327 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005328# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005329 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005330 const struct reserved_combo *r;
5331
5332 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5333 if (strcmp(word->data, r->literal) == 0)
5334 return r;
5335 }
5336 return NULL;
5337}
Denis Vlasenkobb929512009-04-16 10:59:40 +00005338/* Return 0: not a keyword, 1: keyword
5339 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005340static int reserved_word(o_string *word, struct parse_context *ctx)
5341{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005342# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005343 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005344 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005345 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005346# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005347 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005348
Denis Vlasenkobb929512009-04-16 10:59:40 +00005349 if (word->o_quoted)
5350 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005351 r = match_reserved_word(word);
5352 if (!r)
5353 return 0;
5354
5355 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005356# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005357 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5358 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005359 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005360 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005361# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005362 if (r->flag == 0) { /* '!' */
5363 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005364 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00005365 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00005366 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005367 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005368 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005369 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005370 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005371 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005372
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005373 old = xmalloc(sizeof(*old));
5374 debug_printf_parse("push stack %p\n", old);
5375 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005376 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005377 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005378 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005379 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005380 ctx->ctx_res_w = RES_SNTX;
5381 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005382 } else {
5383 /* "{...} fi" is ok. "{...} if" is not
5384 * Example:
5385 * if { echo foo; } then { echo bar; } fi */
5386 if (ctx->command->group)
5387 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005388 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00005389
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005390 ctx->ctx_res_w = r->res;
5391 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005392 word->o_assignment = r->assignment_flag;
5393
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005394 if (ctx->old_flag & FLAG_END) {
5395 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005396
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005397 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005398 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005399 old = ctx->stack;
5400 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005401 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005402# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005403 o_addstr(&old->as_string, ctx->as_string.data);
5404 o_free_unsafe(&ctx->as_string);
5405 old->command->group_as_string = xstrdup(old->as_string.data);
5406 debug_printf_parse("pop, remembering as:'%s'\n",
5407 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005408# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005409 *ctx = *old; /* physical copy */
5410 free(old);
5411 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005412 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005413}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005414#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00005415
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005416/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005417 * Normal return is 0. Syntax errors return 1.
5418 * Note: on return, word is reset, but not o_free'd!
5419 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005420static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005421{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005422 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00005423
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005424 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005425 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005426 debug_printf_parse("done_word return 0: true null, ignored\n");
5427 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005428 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005429
Eric Andersen25f27032001-04-26 23:22:31 +00005430 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005431 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5432 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005433 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5434 * "2.7 Redirection
5435 * ...the word that follows the redirection operator
5436 * shall be subjected to tilde expansion, parameter expansion,
5437 * command substitution, arithmetic expansion, and quote
5438 * removal. Pathname expansion shall not be performed
5439 * on the word by a non-interactive shell; an interactive
5440 * shell may perform it, but shall do so only when
5441 * the expansion would result in one word."
5442 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005443 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005444 /* Cater for >\file case:
5445 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5446 * Same with heredocs:
5447 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5448 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005449 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5450 unbackslash(ctx->pending_redirect->rd_filename);
5451 /* Is it <<"HEREDOC"? */
5452 if (word->o_quoted) {
5453 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5454 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005455 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005456 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005457 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00005458 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005459 /* If this word wasn't an assignment, next ones definitely
5460 * can't be assignments. Even if they look like ones. */
5461 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5462 && word->o_assignment != WORD_IS_KEYWORD
5463 ) {
5464 word->o_assignment = NOT_ASSIGNMENT;
5465 } else {
5466 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5467 command->assignment_cnt++;
5468 word->o_assignment = MAYBE_ASSIGNMENT;
5469 }
5470
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005471#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005472# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00005473 if (ctx->ctx_dsemicolon
5474 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5475 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00005476 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005477 /* ctx->ctx_res_w = RES_MATCH; */
5478 ctx->ctx_dsemicolon = 0;
5479 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005480# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005481 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005482# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005483 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5484 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005485# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005486# if ENABLE_HUSH_CASE
5487 && ctx->ctx_res_w != RES_CASE
5488# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005489 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005490 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005491 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005492 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005493 debug_printf_parse("done_word return %d\n",
5494 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005495 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005496 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005497# ifdef CMD_SINGLEWORD_NOGLOB_COND
5498 if (strcmp(word->data, "export") == 0
5499# if ENABLE_HUSH_LOCAL
5500 || strcmp(word->data, "local") == 0
5501# endif
5502 ) {
5503 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5504 } else
5505# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005506# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005507 if (strcmp(word->data, "[[") == 0) {
5508 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5509 }
5510 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005511# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005512 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005513#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005514 if (command->group) {
5515 /* "{ echo foo; } echo bar" - bad */
5516 syntax_error_at(word->data);
5517 debug_printf_parse("done_word return 1: syntax error, "
5518 "groups and arglists don't mix\n");
5519 return 1;
5520 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005521 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005522 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5523 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005524 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005525 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005526 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005527 char *p = word->data;
5528 while (p[0] == SPECIAL_VAR_SYMBOL
5529 && (p[1] & 0x7f) == '@'
5530 && p[2] == SPECIAL_VAR_SYMBOL
5531 ) {
5532 p += 3;
5533 }
5534 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005535 /* saw no "$@", or not only "$@" but some
5536 * real text is there too */
5537 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005538 * e.g. "", $empty"" etc to not disappear */
5539 o_addchr(word, SPECIAL_VAR_SYMBOL);
5540 o_addchr(word, SPECIAL_VAR_SYMBOL);
5541 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005542 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005543 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005544 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005545 }
Eric Andersen25f27032001-04-26 23:22:31 +00005546
Denis Vlasenko06810332007-05-21 23:30:54 +00005547#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005548 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005549 if (word->o_quoted
5550 || !is_well_formed_var_name(command->argv[0], '\0')
5551 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005552 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005553 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005554 return 1;
5555 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005556 /* Force FOR to have just one word (variable name) */
5557 /* NB: basically, this makes hush see "for v in ..."
5558 * syntax as if it is "for v; in ...". FOR and IN become
5559 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005560 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005561 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005562#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005563#if ENABLE_HUSH_CASE
5564 /* Force CASE to have just one word */
5565 if (ctx->ctx_res_w == RES_CASE) {
5566 done_pipe(ctx, PIPE_SEQ);
5567 }
5568#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005569
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005570 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005571
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005572 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005573 return 0;
5574}
5575
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005576
5577/* Peek ahead in the input to find out if we have a "&n" construct,
5578 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005579 * Return:
5580 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5581 * REDIRFD_SYNTAX_ERR if syntax error,
5582 * REDIRFD_TO_FILE if no & was seen,
5583 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005584 */
5585#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005586#define parse_redir_right_fd(as_string, input) \
5587 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005588#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005589static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005590{
5591 int ch, d, ok;
5592
5593 ch = i_peek(input);
5594 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005595 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005596
5597 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005598 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005599 ch = i_peek(input);
5600 if (ch == '-') {
5601 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005602 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005603 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005604 }
5605 d = 0;
5606 ok = 0;
5607 while (ch != EOF && isdigit(ch)) {
5608 d = d*10 + (ch-'0');
5609 ok = 1;
5610 ch = i_getch(input);
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 }
5614 if (ok) return d;
5615
5616//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5617
5618 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005619 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005620}
5621
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005622/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005623 */
5624static int parse_redirect(struct parse_context *ctx,
5625 int fd,
5626 redir_type style,
5627 struct in_str *input)
5628{
5629 struct command *command = ctx->command;
5630 struct redir_struct *redir;
5631 struct redir_struct **redirp;
5632 int dup_num;
5633
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005634 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005635 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005636 /* Check for a '>&1' type redirect */
5637 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5638 if (dup_num == REDIRFD_SYNTAX_ERR)
5639 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005640 } else {
5641 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005642 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005643 if (dup_num) { /* <<-... */
5644 ch = i_getch(input);
5645 nommu_addchr(&ctx->as_string, ch);
5646 ch = i_peek(input);
5647 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005648 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005649
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005650 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005651 int ch = i_peek(input);
5652 if (ch == '|') {
5653 /* >|FILE redirect ("clobbering" >).
5654 * Since we do not support "set -o noclobber" yet,
5655 * >| and > are the same for now. Just eat |.
5656 */
5657 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005658 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005659 }
5660 }
5661
5662 /* Create a new redir_struct and append it to the linked list */
5663 redirp = &command->redirects;
5664 while ((redir = *redirp) != NULL) {
5665 redirp = &(redir->next);
5666 }
5667 *redirp = redir = xzalloc(sizeof(*redir));
5668 /* redir->next = NULL; */
5669 /* redir->rd_filename = NULL; */
5670 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005671 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005672
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005673 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5674 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005675
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005676 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005677 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005678 /* Erik had a check here that the file descriptor in question
5679 * is legit; I postpone that to "run time"
5680 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005681 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5682 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005683 } else {
5684 /* Set ctx->pending_redirect, so we know what to do at the
5685 * end of the next parsed word. */
5686 ctx->pending_redirect = redir;
5687 }
5688 return 0;
5689}
5690
Eric Andersen25f27032001-04-26 23:22:31 +00005691/* If a redirect is immediately preceded by a number, that number is
5692 * supposed to tell which file descriptor to redirect. This routine
5693 * looks for such preceding numbers. In an ideal world this routine
5694 * needs to handle all the following classes of redirects...
5695 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5696 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5697 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5698 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005699 *
5700 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5701 * "2.7 Redirection
5702 * ... If n is quoted, the number shall not be recognized as part of
5703 * the redirection expression. For example:
5704 * echo \2>a
5705 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005706 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005707 *
5708 * A -1 return means no valid number was found,
5709 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005710 */
5711static int redirect_opt_num(o_string *o)
5712{
5713 int num;
5714
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005715 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005716 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005717 num = bb_strtou(o->data, NULL, 10);
5718 if (errno || num < 0)
5719 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005720 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005721 return num;
5722}
5723
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005724#if BB_MMU
5725#define fetch_till_str(as_string, input, word, skip_tabs) \
5726 fetch_till_str(input, word, skip_tabs)
5727#endif
5728static char *fetch_till_str(o_string *as_string,
5729 struct in_str *input,
5730 const char *word,
5731 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005732{
5733 o_string heredoc = NULL_O_STRING;
5734 int past_EOL = 0;
5735 int ch;
5736
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005737 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005738 while (1) {
5739 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005740 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005741 if (ch == '\n') {
5742 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5743 heredoc.data[past_EOL] = '\0';
5744 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5745 return heredoc.data;
5746 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005747 do {
5748 o_addchr(&heredoc, ch);
5749 past_EOL = heredoc.length;
5750 jump_in:
5751 do {
5752 ch = i_getch(input);
5753 nommu_addchr(as_string, ch);
5754 } while (skip_tabs && ch == '\t');
5755 } while (ch == '\n');
5756 }
5757 if (ch == EOF) {
5758 o_free_unsafe(&heredoc);
5759 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005760 }
5761 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005762 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005763 }
5764}
5765
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005766/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5767 * and load them all. There should be exactly heredoc_cnt of them.
5768 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005769static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5770{
5771 struct pipe *pi = ctx->list_head;
5772
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005773 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005774 int i;
5775 struct command *cmd = pi->cmds;
5776
5777 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5778 pi->num_cmds,
5779 cmd->argv ? cmd->argv[0] : "NONE");
5780 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005781 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005782
5783 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5784 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005785 while (redir) {
5786 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005787 char *p;
5788
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005789 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005790 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005791 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005792 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005793 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005794 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005795 return 1;
5796 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005797 free(redir->rd_filename);
5798 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005799 heredoc_cnt--;
5800 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005801 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005802 }
5803 cmd++;
5804 }
5805 pi = pi->next;
5806 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005807#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005808 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005809 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005810 bb_error_msg_and_die("heredoc BUG 2");
5811#endif
5812 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005813}
5814
5815
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005816#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005817static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005818{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005819 pid_t pid;
5820 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005821# if !BB_MMU
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01005822 char **to_free = NULL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005823# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005824
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005825 xpipe(channel);
Pascal Bellard926031b2010-07-04 15:32:38 +02005826 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko05743d72008-02-10 12:10:08 +00005827 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005828 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005829 /* Process substitution is not considered to be usual
5830 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005831 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5832 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005833 bb_signals(0
5834 + (1 << SIGTSTP)
5835 + (1 << SIGTTIN)
5836 + (1 << SIGTTOU)
5837 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005838 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005839 close(channel[0]); /* NB: close _first_, then move fd! */
5840 xmove_fd(channel[1], 1);
5841 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005842 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005843 /* Awful hack for `trap` or $(trap).
5844 *
5845 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5846 * contains an example where "trap" is executed in a subshell:
5847 *
5848 * save_traps=$(trap)
5849 * ...
5850 * eval "$save_traps"
5851 *
5852 * Standard does not say that "trap" in subshell shall print
5853 * parent shell's traps. It only says that its output
5854 * must have suitable form, but then, in the above example
5855 * (which is not supposed to be normative), it implies that.
5856 *
5857 * bash (and probably other shell) does implement it
5858 * (traps are reset to defaults, but "trap" still shows them),
5859 * but as a result, "trap" logic is hopelessly messed up:
5860 *
5861 * # trap
5862 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5863 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5864 * # true | trap <--- trap is in subshell - no output (ditto)
5865 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5866 * trap -- 'echo Ho' SIGWINCH
5867 * # echo `(trap)` <--- in subshell in subshell - output
5868 * trap -- 'echo Ho' SIGWINCH
5869 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5870 * trap -- 'echo Ho' SIGWINCH
5871 *
5872 * The rules when to forget and when to not forget traps
5873 * get really complex and nonsensical.
5874 *
5875 * Our solution: ONLY bare $(trap) or `trap` is special.
5876 */
5877 s = skip_whitespace(s);
5878 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5879 {
5880 static const char *const argv[] = { NULL, NULL };
5881 builtin_trap((char**)argv);
5882 exit(0); /* not _exit() - we need to fflush */
5883 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005884# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005885 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005886 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005887 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005888# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005889 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005890 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5891 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005892 * echo OK
5893 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005894 re_execute_shell(&to_free,
5895 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005896 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005897 G.global_argv + 1,
5898 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005899# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005900 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005901
5902 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005903 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005904# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005905 G.count_SIGCHLD++;
5906//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 +02005907# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005908 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005909# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005910 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005911# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005912 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005913 close_on_exec_on(channel[0]);
5914 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005915}
5916
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005917/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005918static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005919{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005920 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005921 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005922 pid_t pid;
5923 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005924
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005925 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005926
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005927 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005928 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005929 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005930 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005931 if (ch == '\n') {
5932 eol_cnt++;
5933 continue;
5934 }
5935 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005936 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005937 eol_cnt--;
5938 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005939 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005940 }
5941
Denys Vlasenko647553a2009-11-15 19:58:19 +01005942 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005943 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005944 /* We need to extract exitcode. Test case
5945 * "true; echo `sleep 1; false` $?"
5946 * should print 1 */
5947 safe_waitpid(pid, &status, 0);
5948 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5949 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005950}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005951#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005952
Denys Vlasenkoc2704542009-11-20 19:14:19 +01005953#if !ENABLE_HUSH_FUNCTIONS
5954#define parse_group(dest, ctx, input, ch) \
5955 parse_group(ctx, input, ch)
5956#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005957static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005958 struct in_str *input, int ch)
5959{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005960 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005961 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005962 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005963 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005964 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005965 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005966
5967 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005968#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005969 if (ch == '(' && !dest->o_quoted) {
5970 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005971 if (done_word(dest, ctx))
5972 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005973 if (!command->argv)
5974 goto skip; /* (... */
5975 if (command->argv[1]) { /* word word ... (... */
5976 syntax_error_unexpected_ch('(');
5977 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005978 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005979 /* it is "word(..." or "word (..." */
5980 do
5981 ch = i_getch(input);
5982 while (ch == ' ' || ch == '\t');
5983 if (ch != ')') {
5984 syntax_error_unexpected_ch(ch);
5985 return 1;
5986 }
5987 nommu_addchr(&ctx->as_string, ch);
5988 do
5989 ch = i_getch(input);
5990 while (ch == ' ' || ch == '\t' || ch == '\n');
5991 if (ch != '{') {
5992 syntax_error_unexpected_ch(ch);
5993 return 1;
5994 }
5995 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005996 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005997 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005998 }
5999#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006000
6001#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006002 if (command->argv /* word [word]{... */
6003 || dest->length /* word{... */
6004 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006005 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006006 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006007 debug_printf_parse("parse_group return 1: "
6008 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006009 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006010 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006011#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006012
6013#if ENABLE_HUSH_FUNCTIONS
6014 skip:
6015#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006016 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006017 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00006018 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02006019 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00006020 } else {
6021 /* bash does not allow "{echo...", requires whitespace */
6022 ch = i_getch(input);
6023 if (ch != ' ' && ch != '\t' && ch != '\n') {
6024 syntax_error_unexpected_ch(ch);
6025 return 1;
6026 }
6027 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006028 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006029
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006030 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006031#if BB_MMU
6032# define as_string NULL
6033#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006034 char *as_string = NULL;
6035#endif
6036 pipe_list = parse_stream(&as_string, input, endch);
6037#if !BB_MMU
6038 if (as_string)
6039 o_addstr(&ctx->as_string, as_string);
6040#endif
6041 /* empty ()/{} or parse error? */
6042 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00006043 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006044 if (!BB_MMU)
6045 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006046 debug_printf_parse("parse_group return 1: "
6047 "parse_stream returned %p\n", pipe_list);
6048 return 1;
6049 }
6050 command->group = pipe_list;
6051#if !BB_MMU
6052 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6053 command->group_as_string = as_string;
6054 debug_printf_parse("end of group, remembering as:'%s'\n",
6055 command->group_as_string);
6056#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006057#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006058 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006059 debug_printf_parse("parse_group return 0\n");
6060 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006061 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00006062}
6063
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006064#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006065/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006066static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006067/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006068static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006069{
6070 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006071 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006072 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006073 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006074 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006075 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006076 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006077 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006078 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006079 }
6080}
6081/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006082static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006083{
6084 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006085 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006086 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006087 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006088 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006089 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006090 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006091 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006092 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006093 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006094 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006095 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006096 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006097 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006098 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006099 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006100 continue;
6101 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00006102 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006103 }
6104}
6105/* Process `cmd` - copy contents until "`" is seen. Complicated by
6106 * \` quoting.
6107 * "Within the backquoted style of command substitution, backslash
6108 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6109 * The search for the matching backquote shall be satisfied by the first
6110 * backquote found without a preceding backslash; during this search,
6111 * if a non-escaped backquote is encountered within a shell comment,
6112 * a here-document, an embedded command substitution of the $(command)
6113 * form, or a quoted string, undefined results occur. A single-quoted
6114 * or double-quoted string that begins, but does not end, within the
6115 * "`...`" sequence produces undefined results."
6116 * Example Output
6117 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6118 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006119static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006120{
6121 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006122 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006123 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006124 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006125 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006126 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006127 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006128 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006129 if (ch == '\\') {
6130 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006131 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006132 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006133 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006134 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006135 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006136 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006137 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006138 ch = ch2;
6139 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006140 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006141 }
6142}
6143/* Process $(cmd) - copy contents until ")" is seen. Complicated by
6144 * quoting and nested ()s.
6145 * "With the $(command) style of command substitution, all characters
6146 * following the open parenthesis to the matching closing parenthesis
6147 * constitute the command. Any valid shell script can be used for command,
6148 * except a script consisting solely of redirections which produces
6149 * unspecified results."
6150 * Example Output
6151 * echo $(echo '(TEST)' BEST) (TEST) BEST
6152 * echo $(echo 'TEST)' BEST) TEST) BEST
6153 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02006154 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006155 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006156 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006157 * In bash compat mode, it needs to also be able to stop on '}' or ':'
6158 * for ${var:N[:M]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006159 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006160#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006161static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006162{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006163 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02006164 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006165# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006166 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006167# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006168 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6169
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006170 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006171 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006172 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006173 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006174 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006175 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006176 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006177 if (!dbl)
6178 break;
6179 /* we look for closing )) of $((EXPR)) */
6180 if (i_peek(input) == end_ch) {
6181 i_getch(input); /* eat second ')' */
6182 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006183 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006184 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006185 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006186 if (ch == '(' || ch == '{') {
6187 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006188 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006189 o_addchr(dest, ch);
6190 continue;
6191 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006192 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006193 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006194 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006195 continue;
6196 }
6197 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006198 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006199 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006200 continue;
6201 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006202 if (ch == '`') {
6203 add_till_backquote(dest, input);
6204 o_addchr(dest, ch);
6205 continue;
6206 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006207 if (ch == '\\') {
6208 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006209 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006210 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006211 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006212 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006213 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006214 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006215 continue;
6216 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006217 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006218 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006219}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006220#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006221
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006222/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006223#if BB_MMU
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006224#define parse_dollar(as_string, dest, input) \
6225 parse_dollar(dest, input)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006226#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006227#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006228static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006229 o_string *dest,
6230 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00006231{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006232 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006233 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006234
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006235 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006236 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006237 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006238 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00006239 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006240 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006241 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006242 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006243 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006244 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006245 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006246 if (!isalnum(ch) && ch != '_')
6247 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006248 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006249 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006250 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006251 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006252 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006253 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006254 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006255 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006256 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006257 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006258 o_addchr(dest, ch | quote_mask);
6259 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006260 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006261 case '$': /* pid */
6262 case '!': /* last bg pid */
6263 case '?': /* last exit code */
6264 case '#': /* number of args */
6265 case '*': /* args */
6266 case '@': /* args */
6267 goto make_one_char_var;
6268 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04006269 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6270
Denys Vlasenko74369502010-05-21 19:52:01 +02006271 ch = i_getch(input); /* eat '{' */
6272 nommu_addchr(as_string, ch);
6273
6274 ch = i_getch(input); /* first char after '{' */
6275 nommu_addchr(as_string, ch);
6276 /* It should be ${?}, or ${#var},
6277 * or even ${?+subst} - operator acting on a special variable,
6278 * or the beginning of variable name.
6279 */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02006280 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
Denys Vlasenko74369502010-05-21 19:52:01 +02006281 bad_dollar_syntax:
6282 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006283 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02006284 return 1;
6285 }
6286 ch |= quote_mask;
6287
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006288 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02006289 * However, this regresses some of our testsuite cases
6290 * which check invalid constructs like ${%}.
6291 * Oh well... let's check that the var name part is fine... */
6292
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006293 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006294 unsigned pos;
6295
Denys Vlasenko74369502010-05-21 19:52:01 +02006296 o_addchr(dest, ch);
6297 debug_printf_parse(": '%c'\n", ch);
6298
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006299 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006300 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02006301 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00006302 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006303
Denys Vlasenko74369502010-05-21 19:52:01 +02006304 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006305 unsigned end_ch;
6306 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006307 /* handle parameter expansions
6308 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6309 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006310 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6311 goto bad_dollar_syntax;
Denys Vlasenko74369502010-05-21 19:52:01 +02006312 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006313
6314 /* Eat everything until closing '}' (or ':') */
6315 end_ch = '}';
6316 if (ENABLE_HUSH_BASH_COMPAT
6317 && ch == ':'
6318 && !strchr("%#:-=+?"+3, i_peek(input))
6319 ) {
6320 /* It's ${var:N[:M]} thing */
6321 end_ch = '}' * 0x100 + ':';
6322 }
6323 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006324 if (!BB_MMU)
6325 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006326#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006327 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006328#else
6329#error Simple code to only allow ${var} is not implemented
6330#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006331 if (as_string) {
6332 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006333 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006334 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006335
6336 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6337 /* close the first block: */
6338 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6339 /* while parsing N from ${var:N[:M]}... */
6340 if ((end_ch & 0xff) == last_ch) {
6341 /* ...got ':' - parse the rest */
6342 end_ch = '}';
6343 goto again;
6344 }
6345 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6346 o_addstr(dest, "999999999");
6347 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006348 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006349 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006350 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006351 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6352 break;
6353 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006354#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006355 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006356 unsigned pos;
6357
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006358 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006359 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006360# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006361 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006362 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006363 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006364 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6365 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006366 if (!BB_MMU)
6367 pos = dest->length;
6368 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006369 if (as_string) {
6370 o_addstr(as_string, dest->data + pos);
6371 o_addchr(as_string, ')');
6372 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006373 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006374 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006375 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006376 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006377# endif
6378# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006379 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6380 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006381 if (!BB_MMU)
6382 pos = dest->length;
6383 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006384 if (as_string) {
6385 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006386 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006387 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006388 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006389# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006390 break;
6391 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006392#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006393 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006394 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006395 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006396 ch = i_peek(input);
6397 if (isalnum(ch)) { /* it's $_name or $_123 */
6398 ch = '_';
6399 goto make_var;
6400 }
6401 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02006402 /* TODO: $_ and $-: */
6403 /* $_ Shell or shell script name; or last argument of last command
6404 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6405 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006406 /* $- Option flags set by set builtin or shell options (-i etc) */
6407 default:
6408 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00006409 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006410 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00006411 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006412#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00006413}
6414
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006415#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006416#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006417 parse_stream_dquoted(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006418#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006419#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006420static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006421 o_string *dest,
6422 struct in_str *input,
6423 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006424{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006425 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006426 int next;
6427
6428 again:
6429 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006430 if (ch != EOF)
6431 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006432 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006433 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006434 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006435 debug_printf_parse("parse_stream_dquoted return 0\n");
6436 return 0;
6437 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006438 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006439 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006440 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006441 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006442 }
6443 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006444 if (ch != '\n') {
6445 next = i_peek(input);
6446 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006447 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006448 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006449 if (ch == '\\') {
6450 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006451 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006452 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006453 }
6454 /* bash:
6455 * "The backslash retains its special meaning [in "..."]
6456 * only when followed by one of the following characters:
6457 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006458 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006459 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006460 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00006461 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006462 if (ch != '\n') {
6463 o_addqchr(dest, ch);
6464 nommu_addchr(as_string, ch);
6465 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006466 } else {
6467 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00006468 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006469 }
6470 goto again;
6471 }
6472 if (ch == '$') {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006473 if (parse_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006474 debug_printf_parse("parse_stream_dquoted return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006475 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006476 return 1;
6477 }
6478 goto again;
6479 }
6480#if ENABLE_HUSH_TICK
6481 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006482 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006483 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6484 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006485 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006486 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6487 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00006488 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006489 }
6490#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00006491 o_addQchr(dest, ch);
6492 if (ch == '='
6493 && (dest->o_assignment == MAYBE_ASSIGNMENT
6494 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006495 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00006496 ) {
6497 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6498 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006499 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006500#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006501}
6502
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006503/*
6504 * Scan input until EOF or end_trigger char.
6505 * Return a list of pipes to execute, or NULL on EOF
6506 * or if end_trigger character is met.
6507 * On syntax error, exit is shell is not interactive,
6508 * reset parsing machinery and start parsing anew,
6509 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006510 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006511static struct pipe *parse_stream(char **pstring,
6512 struct in_str *input,
6513 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006514{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006515 struct parse_context ctx;
6516 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006517 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006518 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006519
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006520 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006521 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006522 * found. When recursing, quote state is passed in via dest->o_escape.
6523 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006524 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006525 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006526 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006527
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006528 /* If very first arg is "" or '', dest.data may end up NULL.
6529 * Preventing this: */
6530 o_addchr(&dest, '\0');
6531 dest.length = 0;
6532
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006533 G.ifs = get_local_var_value("IFS");
6534 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01006535 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006536
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006537 reset:
6538#if ENABLE_HUSH_INTERACTIVE
6539 input->promptmode = 0; /* PS1 */
6540#endif
6541 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6542 initialize_context(&ctx);
6543 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006544 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006545 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006546 const char *is_ifs;
6547 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006548 int ch;
6549 int next;
6550 int redir_fd;
6551 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006552
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006553 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006554 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006555 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006556 goto parse_error;
6557 }
6558 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006559 is_in_dquote = 0;
6560 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006561 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006562 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6563 ch, ch, dest.o_escape);
6564 if (ch == EOF) {
6565 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006566
6567 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006568 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006569 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006570 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006571 /* end_trigger == '}' case errors out earlier,
6572 * checking only ')' */
6573 if (end_trigger == ')') {
6574 syntax_error_unterm_ch('('); /* exits */
6575 /* goto parse_error; */
6576 }
6577
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006578 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006579 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006580 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006581 o_free(&dest);
6582 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006583 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006584 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006585 /* (this makes bare "&" cmd a no-op.
6586 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006587 if (pi->num_cmds == 0
6588 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6589 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006590 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006591 pi = NULL;
6592 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006593#if !BB_MMU
6594 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6595 if (pstring)
6596 *pstring = ctx.as_string.data;
6597 else
6598 o_free_unsafe(&ctx.as_string);
6599#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006600 debug_leave();
6601 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006602 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006603 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006604 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006605
6606 next = '\0';
6607 if (ch != '\n')
6608 next = i_peek(input);
6609
6610 is_special = "{}<>;&|()#'" /* special outside of "str" */
6611 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6612 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02006613 if (ctx.command->argv /* word [word]{... - non-special */
6614 || dest.length /* word{... - non-special */
6615 || dest.o_quoted /* ""{... - non-special */
6616 || (next != ';' /* }; - special */
6617 && next != ')' /* }) - special */
6618 && next != '&' /* }& and }&& ... - special */
6619 && next != '|' /* }|| ... - special */
6620 && !strchr(G.ifs, next) /* {word - non-special */
6621 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006622 ) {
6623 /* They are not special, skip "{}" */
6624 is_special += 2;
6625 }
6626 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006627 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006628
6629 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006630 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006631 o_addQchr(&dest, ch);
6632 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6633 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006634 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006635 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006636 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006637 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006638 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006639 continue;
6640 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006641
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006642 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006643 if (done_word(&dest, &ctx)) {
6644 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006645 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006646 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006647#if ENABLE_HUSH_CASE
6648 /* "case ... in <newline> word) ..." -
6649 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006650 if (ctx.command->argv == NULL
6651 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006652 ) {
6653 continue;
6654 }
6655#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006656 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006657 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006658 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6659 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006660 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006661 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006662 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006663 heredoc_cnt = 0;
6664 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006665 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006666 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006667 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006668 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006669 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006670 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006671
6672 /* "cmd}" or "cmd }..." without semicolon or &:
6673 * } is an ordinary char in this case, even inside { cmd; }
6674 * Pathological example: { ""}; } should exec "}" cmd
6675 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006676 if (ch == '}') {
6677 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6678 || dest.length != 0 /* word} */
6679 || dest.o_quoted /* ""} */
6680 ) {
6681 goto ordinary_char;
6682 }
6683 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6684 goto skip_end_trigger;
6685 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006686 }
6687
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006688 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006689 && (ch != ';' || heredoc_cnt == 0)
6690#if ENABLE_HUSH_CASE
6691 && (ch != ')'
6692 || ctx.ctx_res_w != RES_MATCH
6693 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6694 )
6695#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006696 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006697 if (heredoc_cnt) {
6698 /* This is technically valid:
6699 * { cat <<HERE; }; echo Ok
6700 * heredoc
6701 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006702 * HERE
6703 * but we don't support this.
6704 * We require heredoc to be in enclosing {}/(),
6705 * if any.
6706 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006707 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006708 goto parse_error;
6709 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006710 if (done_word(&dest, &ctx)) {
6711 goto parse_error;
6712 }
6713 done_pipe(&ctx, PIPE_SEQ);
6714 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006715 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006716 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006717 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006718 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006719 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006720#if !BB_MMU
6721 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6722 if (pstring)
6723 *pstring = ctx.as_string.data;
6724 else
6725 o_free_unsafe(&ctx.as_string);
6726#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006727 debug_leave();
6728 debug_printf_parse("parse_stream return %p: "
6729 "end_trigger char found\n",
6730 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006731 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006732 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006733 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006734 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006735 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006736 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006737
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006738 /* Catch <, > before deciding whether this word is
6739 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6740 switch (ch) {
6741 case '>':
6742 redir_fd = redirect_opt_num(&dest);
6743 if (done_word(&dest, &ctx)) {
6744 goto parse_error;
6745 }
6746 redir_style = REDIRECT_OVERWRITE;
6747 if (next == '>') {
6748 redir_style = REDIRECT_APPEND;
6749 ch = i_getch(input);
6750 nommu_addchr(&ctx.as_string, ch);
6751 }
6752#if 0
6753 else if (next == '(') {
6754 syntax_error(">(process) not supported");
6755 goto parse_error;
6756 }
6757#endif
6758 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6759 goto parse_error;
6760 continue; /* back to top of while (1) */
6761 case '<':
6762 redir_fd = redirect_opt_num(&dest);
6763 if (done_word(&dest, &ctx)) {
6764 goto parse_error;
6765 }
6766 redir_style = REDIRECT_INPUT;
6767 if (next == '<') {
6768 redir_style = REDIRECT_HEREDOC;
6769 heredoc_cnt++;
6770 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6771 ch = i_getch(input);
6772 nommu_addchr(&ctx.as_string, ch);
6773 } else if (next == '>') {
6774 redir_style = REDIRECT_IO;
6775 ch = i_getch(input);
6776 nommu_addchr(&ctx.as_string, ch);
6777 }
6778#if 0
6779 else if (next == '(') {
6780 syntax_error("<(process) not supported");
6781 goto parse_error;
6782 }
6783#endif
6784 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6785 goto parse_error;
6786 continue; /* back to top of while (1) */
6787 }
6788
6789 if (dest.o_assignment == MAYBE_ASSIGNMENT
6790 /* check that we are not in word in "a=1 2>word b=1": */
6791 && !ctx.pending_redirect
6792 ) {
6793 /* ch is a special char and thus this word
6794 * cannot be an assignment */
6795 dest.o_assignment = NOT_ASSIGNMENT;
6796 }
6797
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006798 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6799
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006800 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006801 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006802 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006803 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006804 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006805 if (ch == EOF || ch == '\n')
6806 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006807 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006808 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006809 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006810 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006811 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006812 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006813 }
6814 break;
6815 case '\\':
6816 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006817 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006818 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006819 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006820 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006821 if (ch != '\n') {
6822 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006823 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006824 o_addchr(&dest, ch);
6825 nommu_addchr(&ctx.as_string, ch);
6826 /* Example: echo Hello \2>file
6827 * we need to know that word 2 is quoted */
6828 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006829 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006830#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006831 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006832 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6833 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006834 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006835#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006836 break;
6837 case '$':
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006838 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006839 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006840 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006841 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006842 }
Eric Andersen25f27032001-04-26 23:22:31 +00006843 break;
6844 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006845 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006846 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006847 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006848 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006849 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006850 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006851 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006852 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006853 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006854 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006855 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006856 }
Eric Andersen25f27032001-04-26 23:22:31 +00006857 break;
6858 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006859 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006860 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006861 if (dest.o_assignment == NOT_ASSIGNMENT)
6862 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006863 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006864#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006865 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006866 unsigned pos;
6867
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006868 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6869 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006870 pos = dest.length;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006871 add_till_backquote(&dest, input);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006872# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006873 o_addstr(&ctx.as_string, dest.data + pos);
6874 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006875# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006876 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6877 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006878 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006879 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006880#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006881 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006882#if ENABLE_HUSH_CASE
6883 case_semi:
6884#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006885 if (done_word(&dest, &ctx)) {
6886 goto parse_error;
6887 }
6888 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006889#if ENABLE_HUSH_CASE
6890 /* Eat multiple semicolons, detect
6891 * whether it means something special */
6892 while (1) {
6893 ch = i_peek(input);
6894 if (ch != ';')
6895 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006896 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006897 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006898 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006899 ctx.ctx_dsemicolon = 1;
6900 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006901 break;
6902 }
6903 }
6904#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006905 new_cmd:
6906 /* We just finished a cmd. New one may start
6907 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006908 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006909 break;
6910 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006911 if (done_word(&dest, &ctx)) {
6912 goto parse_error;
6913 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006914 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006915 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006916 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006917 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006918 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006919 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006920 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006921 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006922 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006923 if (done_word(&dest, &ctx)) {
6924 goto parse_error;
6925 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006926#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006927 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006928 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006929#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006930 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006931 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006932 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006933 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006934 } else {
6935 /* we could pick up a file descriptor choice here
6936 * with redirect_opt_num(), but bash doesn't do it.
6937 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006938 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006939#if !BB_MMU
6940 o_reset_to_empty_unquoted(&ctx.as_string);
6941#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006942 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006943 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006944 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006945#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006946 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006947 if (ctx.ctx_res_w == RES_MATCH
6948 && ctx.command->argv == NULL /* not (word|(... */
6949 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006950 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006951 ) {
6952 continue;
6953 }
6954#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006955 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006956 if (parse_group(&dest, &ctx, input, ch) != 0) {
6957 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006958 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006959 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006960 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006961#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006962 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006963 goto case_semi;
6964#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006965 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006966 /* proper use of this character is caught by end_trigger:
6967 * if we see {, we call parse_group(..., end_trigger='}')
6968 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006969 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006970 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006971 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006972 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006973 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006974 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006975 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006976
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006977 parse_error:
6978 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006979 struct parse_context *pctx;
6980 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006981
6982 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006983 * Sample for finding leaks on syntax error recovery path.
6984 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006985 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006986 * Samples to catch leaks at execution:
6987 * while if (true | {true;}); then echo ok; fi; do break; done
6988 * 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 +00006989 */
6990 pctx = &ctx;
6991 do {
6992 /* Update pipe/command counts,
6993 * otherwise freeing may miss some */
6994 done_pipe(pctx, PIPE_SEQ);
6995 debug_printf_clean("freeing list %p from ctx %p\n",
6996 pctx->list_head, pctx);
6997 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006998 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006999 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007000#if !BB_MMU
7001 o_free_unsafe(&pctx->as_string);
7002#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007003 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007004 if (pctx != &ctx) {
7005 free(pctx);
7006 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007007 IF_HAS_KEYWORDS(pctx = p2;)
7008 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007009 /* Free text, clear all dest fields */
7010 o_free(&dest);
7011 /* If we are not in top-level parse, we return,
7012 * our caller will propagate error.
7013 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007014 if (end_trigger != ';') {
7015#if !BB_MMU
7016 if (pstring)
7017 *pstring = NULL;
7018#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00007019 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007020 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007021 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007022 /* Discard cached input, force prompt */
7023 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007024 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007025 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00007026 }
Eric Andersen25f27032001-04-26 23:22:31 +00007027}
7028
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007029/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007030 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7031 * end_trigger controls how often we stop parsing
7032 * NUL: parse all, execute, return
7033 * ';': parse till ';' or newline, execute, repeat till EOF
7034 */
7035static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007036{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007037 /* Why we need empty flag?
7038 * An obscure corner case "false; ``; echo $?":
7039 * empty command in `` should still set $? to 0.
7040 * But we can't just set $? to 0 at the start,
7041 * this breaks "false; echo `echo $?`" case.
7042 */
7043 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007044 while (1) {
7045 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007046
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007047 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007048 if (!pipe_list) { /* EOF */
7049 if (empty)
7050 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007051 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007052 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007053 debug_print_tree(pipe_list, 0);
7054 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7055 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007056 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007057 }
Eric Andersen25f27032001-04-26 23:22:31 +00007058}
7059
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007060static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007061{
7062 struct in_str input;
7063 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007064 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00007065}
7066
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007067static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00007068{
Eric Andersen25f27032001-04-26 23:22:31 +00007069 struct in_str input;
7070 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007071 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00007072}
7073
Denis Vlasenkof9375282009-04-05 19:13:39 +00007074/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007075static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007076{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007077 unsigned sig;
7078 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007079 sigset_t old_blocked_set;
7080
7081 if (!G.inherited_set_is_saved) {
7082 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7083 G.inherited_set = G.blocked_set;
7084 }
7085 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007086
Denis Vlasenkof9375282009-04-05 19:13:39 +00007087 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007088 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007089 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007090 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007091 mask |= SPECIAL_JOB_SIGS;
7092 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007093 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007094
Denis Vlasenkof9375282009-04-05 19:13:39 +00007095 sig = 0;
7096 while (mask) {
7097 if (mask & 1)
7098 sigaddset(&G.blocked_set, sig);
7099 mask >>= 1;
7100 sig++;
7101 }
7102 sigdelset(&G.blocked_set, SIGCHLD);
7103
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007104 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7105 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7106
Denis Vlasenkof9375282009-04-05 19:13:39 +00007107 /* POSIX allows shell to re-enable SIGCHLD
7108 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007109#if ENABLE_HUSH_FAST
7110 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007111 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007112 signal(SIGCHLD, SIGCHLD_handler);
7113#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007114 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007115 signal(SIGCHLD, SIG_DFL);
7116#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007117
7118 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007119}
7120
7121#if ENABLE_HUSH_JOB
7122/* helper */
7123static void maybe_set_to_sigexit(int sig)
7124{
7125 void (*handler)(int);
7126 /* non_DFL_mask'ed signals are, well, masked,
7127 * no need to set handler for them.
7128 */
7129 if (!((G.non_DFL_mask >> sig) & 1)) {
7130 handler = signal(sig, sigexit);
7131 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7132 signal(sig, handler);
7133 }
7134}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007135/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007136static void set_fatal_handlers(void)
7137{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007138 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007139 if (HUSH_DEBUG) {
7140 maybe_set_to_sigexit(SIGILL );
7141 maybe_set_to_sigexit(SIGFPE );
7142 maybe_set_to_sigexit(SIGBUS );
7143 maybe_set_to_sigexit(SIGSEGV);
7144 maybe_set_to_sigexit(SIGTRAP);
7145 } /* else: hush is perfect. what SEGV? */
7146 maybe_set_to_sigexit(SIGABRT);
7147 /* bash 3.2 seems to handle these just like 'fatal' ones */
7148 maybe_set_to_sigexit(SIGPIPE);
7149 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007150 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007151 * if we aren't interactive... but in this case
7152 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007153 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007154 /*maybe_set_to_sigexit(SIGTERM);*/
7155 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007156}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007157#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007158
Denis Vlasenkod5762932009-03-31 11:22:57 +00007159static int set_mode(const char cstate, const char mode)
7160{
7161 int state = (cstate == '-' ? 1 : 0);
7162 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007163 case 'n': G.n_mode = state; break;
7164 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007165 default: return EXIT_FAILURE;
7166 }
7167 return EXIT_SUCCESS;
7168}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007169
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007170int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007171int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007172{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007173 static const struct variable const_shell_ver = {
7174 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00007175 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007176 .max_len = 1, /* 0 can provoke free(name) */
7177 .flg_export = 1,
7178 .flg_read_only = 1,
7179 };
Eric Andersen25f27032001-04-26 23:22:31 +00007180 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007181 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007182 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007183 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00007184
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007185 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007186 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007187 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007188#if !BB_MMU
7189 G.argv0_for_re_execing = argv[0];
7190#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007191 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007192 G.shell_ver = const_shell_ver; /* copying struct here */
7193 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007194 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007195 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7196 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007197 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007198 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007199 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007200 if (e) while (*e) {
7201 char *value = strchr(*e, '=');
7202 if (value) { /* paranoia */
7203 cur_var->next = xzalloc(sizeof(*cur_var));
7204 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007205 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007206 cur_var->max_len = strlen(*e);
7207 cur_var->flg_export = 1;
7208 }
7209 e++;
7210 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007211 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007212 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007213 putenv((char *)hush_version_str);
7214
7215 /* Export PWD */
7216 set_pwd_var(/*exp:*/ 1);
7217 /* bash also exports SHLVL and _,
7218 * and sets (but doesn't export) the following variables:
7219 * BASH=/bin/bash
7220 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7221 * BASH_VERSION='3.2.0(1)-release'
7222 * HOSTTYPE=i386
7223 * MACHTYPE=i386-pc-linux-gnu
7224 * OSTYPE=linux-gnu
7225 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007226 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007227 * EUID=<NNNNN>
7228 * UID=<NNNNN>
7229 * GROUPS=()
7230 * LINES=<NNN>
7231 * COLUMNS=<NNN>
7232 * BASH_ARGC=()
7233 * BASH_ARGV=()
7234 * BASH_LINENO=()
7235 * BASH_SOURCE=()
7236 * DIRSTACK=()
7237 * PIPESTATUS=([0]="0")
7238 * HISTFILE=/<xxx>/.bash_history
7239 * HISTFILESIZE=500
7240 * HISTSIZE=500
7241 * MAILCHECK=60
7242 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7243 * SHELL=/bin/bash
7244 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7245 * TERM=dumb
7246 * OPTERR=1
7247 * OPTIND=1
7248 * IFS=$' \t\n'
7249 * PS1='\s-\v\$ '
7250 * PS2='> '
7251 * PS4='+ '
7252 */
7253
Denis Vlasenko38f63192007-01-22 09:03:07 +00007254#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007255 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007256#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007257 G.global_argc = argc;
7258 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007259 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007260 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007261
Denis Vlasenkoed782372009-04-10 00:45:02 +00007262 if (setjmp(die_jmp)) {
7263 /* xfunc has failed! die die die */
7264 /* no EXIT traps, this is an escape hatch! */
7265 G.exiting = 1;
7266 hush_exit(xfunc_error_retval);
7267 }
7268
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007269 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007270 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007271 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007272 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007273 * in order to intercept (more) signals.
7274 */
7275
7276 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007277 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007278 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007279 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007280 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007281#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007282 "<:$:R:V:"
7283# if ENABLE_HUSH_FUNCTIONS
7284 "F:"
7285# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007286#endif
7287 );
7288 if (opt <= 0)
7289 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007290 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007291 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007292 /* Possibilities:
7293 * sh ... -c 'script'
7294 * sh ... -c 'script' ARG0 [ARG1...]
7295 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007296 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007297 * "" needs to be replaced with NULL
7298 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007299 * Note: the form without ARG0 never happens:
7300 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007301 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007302 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007303 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007304 G.root_ppid = getppid();
7305 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007306 G.global_argv = argv + optind;
7307 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007308 if (builtin_argc) {
7309 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7310 const struct built_in_command *x;
7311
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007312 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007313 x = find_builtin(optarg);
7314 if (x) { /* paranoia */
7315 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7316 G.global_argv += builtin_argc;
7317 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007318 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007319 }
7320 goto final_return;
7321 }
7322 if (!G.global_argv[0]) {
7323 /* -c 'script' (no params): prevent empty $0 */
7324 G.global_argv--; /* points to argv[i] of 'script' */
7325 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007326 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007327 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007328 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007329 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007330 goto final_return;
7331 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007332 /* Well, we cannot just declare interactiveness,
7333 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007334 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007335 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007336 case 's':
7337 /* "-s" means "read from stdin", but this is how we always
7338 * operate, so simply do nothing here. */
7339 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007340#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007341 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007342 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007343 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007344 case '$': {
7345 unsigned long long empty_trap_mask;
7346
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007347 G.root_pid = bb_strtou(optarg, &optarg, 16);
7348 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007349 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7350 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007351 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7352 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007353 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007354 optarg++;
7355 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007356 optarg++;
7357 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7358 if (empty_trap_mask != 0) {
7359 int sig;
7360 init_sigmasks();
7361 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7362 for (sig = 1; sig < NSIG; sig++) {
7363 if (empty_trap_mask & (1LL << sig)) {
7364 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7365 sigaddset(&G.blocked_set, sig);
7366 }
7367 }
7368 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7369 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007370# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007371 optarg++;
7372 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007373# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007374 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007375 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007376 case 'R':
7377 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007378 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007379 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007380# if ENABLE_HUSH_FUNCTIONS
7381 case 'F': {
7382 struct function *funcp = new_function(optarg);
7383 /* funcp->name is already set to optarg */
7384 /* funcp->body is set to NULL. It's a special case. */
7385 funcp->body_as_string = argv[optind];
7386 optind++;
7387 break;
7388 }
7389# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007390#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007391 case 'n':
7392 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007393 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007394 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007395 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007396#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007397 fprintf(stderr, "Usage: sh [FILE]...\n"
7398 " or: sh -c command [args]...\n\n");
7399 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007400#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007401 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007402#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007403 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007404 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007405
Denys Vlasenkodea47882009-10-09 15:40:49 +02007406 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007407 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007408 G.root_ppid = getppid();
7409 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007410
7411 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007412 if (argv[0] && argv[0][0] == '-') {
7413 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007414 debug_printf("sourcing /etc/profile\n");
7415 input = fopen_for_read("/etc/profile");
7416 if (input != NULL) {
7417 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007418 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007419 parse_and_run_file(input);
7420 fclose(input);
7421 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007422 /* bash: after sourcing /etc/profile,
7423 * tries to source (in the given order):
7424 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007425 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007426 * bash also sources ~/.bash_logout on exit.
7427 * If called as sh, skips .bash_XXX files.
7428 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007429 }
7430
Denis Vlasenkof9375282009-04-05 19:13:39 +00007431 if (argv[optind]) {
7432 FILE *input;
7433 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007434 * "bash <script>" (which is never interactive (unless -i?))
7435 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007436 * If called as sh, does the same but with $ENV.
7437 */
7438 debug_printf("running script '%s'\n", argv[optind]);
7439 G.global_argv = argv + optind;
7440 G.global_argc = argc - optind;
7441 input = xfopen_for_read(argv[optind]);
7442 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007443 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007444 parse_and_run_file(input);
7445#if ENABLE_FEATURE_CLEAN_UP
7446 fclose(input);
7447#endif
7448 goto final_return;
7449 }
7450
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007451 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007452 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007453 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007454
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007455 /* A shell is interactive if the '-i' flag was given,
7456 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007457 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007458 * no arguments remaining or the -s flag given
7459 * standard input is a terminal
7460 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007461 * Refer to Posix.2, the description of the 'sh' utility.
7462 */
7463#if ENABLE_HUSH_JOB
7464 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007465 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7466 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7467 if (G_saved_tty_pgrp < 0)
7468 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007469
7470 /* try to dup stdin to high fd#, >= 255 */
7471 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7472 if (G_interactive_fd < 0) {
7473 /* try to dup to any fd */
7474 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007475 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007476 /* give up */
7477 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007478 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007479 }
7480 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007481// TODO: track & disallow any attempts of user
7482// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007483 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007484 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007485 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007486 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007487
Mike Frysinger38478a62009-05-20 04:48:06 -04007488 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007489 /* If we were run as 'hush &', sleep until we are
7490 * in the foreground (tty pgrp == our pgrp).
7491 * If we get started under a job aware app (like bash),
7492 * make sure we are now in charge so we don't fight over
7493 * who gets the foreground */
7494 while (1) {
7495 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007496 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7497 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007498 break;
7499 /* send TTIN to ourself (should stop us) */
7500 kill(- shell_pgrp, SIGTTIN);
7501 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007502 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007503
Denis Vlasenkof9375282009-04-05 19:13:39 +00007504 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007505 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007506
Mike Frysinger38478a62009-05-20 04:48:06 -04007507 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007508 /* Set other signals to restore saved_tty_pgrp */
7509 set_fatal_handlers();
7510 /* Put ourselves in our own process group
7511 * (bash, too, does this only if ctty is available) */
7512 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7513 /* Grab control of the terminal */
7514 tcsetpgrp(G_interactive_fd, getpid());
7515 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007516 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007517 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007518 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007519 } else {
7520 init_sigmasks();
7521 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007522#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007523 /* No job control compiled in, only prompt/line editing */
7524 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007525 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7526 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007527 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007528 G_interactive_fd = dup(STDIN_FILENO);
7529 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007530 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007531 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007532 }
7533 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007534 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007535 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007536 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007537 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007538#else
7539 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007540 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007541#endif
7542 /* bash:
7543 * if interactive but not a login shell, sources ~/.bashrc
7544 * (--norc turns this off, --rcfile <file> overrides)
7545 */
7546
7547 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007548 /* note: ash and hush share this string */
7549 printf("\n\n%s %s\n"
7550 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7551 "\n",
7552 bb_banner,
7553 "hush - the humble shell"
7554 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007555 }
7556
Denis Vlasenkof9375282009-04-05 19:13:39 +00007557 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007558
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007559 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007560#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007561 if (G.cwd != bb_msg_unknown)
7562 free((char*)G.cwd);
7563 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007564 while (cur_var) {
7565 struct variable *tmp = cur_var;
7566 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007567 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007568 cur_var = cur_var->next;
7569 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007570 }
Eric Andersen25f27032001-04-26 23:22:31 +00007571#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007572 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007573}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007574
7575
7576#if ENABLE_LASH
7577int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7578int lash_main(int argc, char **argv)
7579{
Denys Vlasenko07934912009-08-20 03:40:04 +02007580 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007581 return hush_main(argc, argv);
7582}
7583#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007584
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007585#if ENABLE_MSH
7586int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7587int msh_main(int argc, char **argv)
7588{
7589 //bb_error_msg("msh is deprecated, please use hush instead");
7590 return hush_main(argc, argv);
7591}
7592#endif
7593
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007594
7595/*
7596 * Built-ins
7597 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007598static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007599{
7600 return 0;
7601}
7602
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007603static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007604{
7605 int argc = 0;
7606 while (*argv) {
7607 argc++;
7608 argv++;
7609 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007610 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007611}
7612
7613static int FAST_FUNC builtin_test(char **argv)
7614{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007615 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007616}
7617
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007618static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007619{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007620 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007621}
7622
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007623#if ENABLE_PRINTF
7624static int FAST_FUNC builtin_printf(char **argv)
7625{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007626 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007627}
7628#endif
7629
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007630static char **skip_dash_dash(char **argv)
7631{
7632 argv++;
7633 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7634 argv++;
7635 return argv;
7636}
7637
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007638static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007639{
7640 int rcode = EXIT_SUCCESS;
7641
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007642 argv = skip_dash_dash(argv);
7643 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007644 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007645 /* bash:
7646 * eval "echo Hi; done" ("done" is syntax error):
7647 * "echo Hi" will not execute too.
7648 */
7649 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007650 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007651 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007652 }
7653 return rcode;
7654}
7655
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007656static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007657{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007658 const char *newdir;
7659
7660 argv = skip_dash_dash(argv);
7661 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007662 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007663 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007664 * bash says "bash: cd: HOME not set" and does nothing
7665 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007666 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007667 const char *home = get_local_var_value("HOME");
7668 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007669 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007670 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007671 /* Mimic bash message exactly */
7672 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007673 return EXIT_FAILURE;
7674 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007675 /* Read current dir (get_cwd(1) is inside) and set PWD.
7676 * Note: do not enforce exporting. If PWD was unset or unexported,
7677 * set it again, but do not export. bash does the same.
7678 */
7679 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007680 return EXIT_SUCCESS;
7681}
7682
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007683static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007684{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007685 argv = skip_dash_dash(argv);
7686 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007687 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007688
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007689 /* Careful: we can end up here after [v]fork. Do not restore
7690 * tty pgrp then, only top-level shell process does that */
7691 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7692 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7693
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007694 /* TODO: if exec fails, bash does NOT exit! We do.
7695 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7696 * and tcsetpgrp, and this is inherently racy.
7697 */
7698 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007699}
7700
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007701static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007702{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007703 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007704
7705 /* interactive bash:
7706 * # trap "echo EEE" EXIT
7707 * # exit
7708 * exit
7709 * There are stopped jobs.
7710 * (if there are _stopped_ jobs, running ones don't count)
7711 * # exit
7712 * exit
7713 # EEE (then bash exits)
7714 *
7715 * we can use G.exiting = -1 as indicator "last cmd was exit"
7716 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007717
7718 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007719 argv = skip_dash_dash(argv);
7720 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007721 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007722 /* mimic bash: exit 123abc == exit 255 + error msg */
7723 xfunc_error_retval = 255;
7724 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007725 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007726}
7727
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007728static void print_escaped(const char *s)
7729{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007730 if (*s == '\'')
7731 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007732 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007733 const char *p = strchrnul(s, '\'');
7734 /* print 'xxxx', possibly just '' */
7735 printf("'%.*s'", (int)(p - s), s);
7736 if (*p == '\0')
7737 break;
7738 s = p;
7739 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007740 /* s points to '; print "'''...'''" */
7741 putchar('"');
7742 do putchar('\''); while (*++s == '\'');
7743 putchar('"');
7744 } while (*s);
7745}
7746
Denys Vlasenko295fef82009-06-03 12:47:26 +02007747#if !ENABLE_HUSH_LOCAL
7748#define helper_export_local(argv, exp, lvl) \
7749 helper_export_local(argv, exp)
7750#endif
7751static void helper_export_local(char **argv, int exp, int lvl)
7752{
7753 do {
7754 char *name = *argv;
7755
7756 /* So far we do not check that name is valid (TODO?) */
7757
7758 if (strchr(name, '=') == NULL) {
7759 struct variable *var;
7760
7761 var = get_local_var(name);
7762 if (exp == -1) { /* unexporting? */
7763 /* export -n NAME (without =VALUE) */
7764 if (var) {
7765 var->flg_export = 0;
7766 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7767 unsetenv(name);
7768 } /* else: export -n NOT_EXISTING_VAR: no-op */
7769 continue;
7770 }
7771 if (exp == 1) { /* exporting? */
7772 /* export NAME (without =VALUE) */
7773 if (var) {
7774 var->flg_export = 1;
7775 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7776 putenv(var->varstr);
7777 continue;
7778 }
7779 }
7780 /* Exporting non-existing variable.
7781 * bash does not put it in environment,
7782 * but remembers that it is exported,
7783 * and does put it in env when it is set later.
7784 * We just set it to "" and export. */
7785 /* Or, it's "local NAME" (without =VALUE).
7786 * bash sets the value to "". */
7787 name = xasprintf("%s=", name);
7788 } else {
7789 /* (Un)exporting/making local NAME=VALUE */
7790 name = xstrdup(name);
7791 }
7792 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7793 } while (*++argv);
7794}
7795
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007796static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007797{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007798 unsigned opt_unexport;
7799
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007800#if ENABLE_HUSH_EXPORT_N
7801 /* "!": do not abort on errors */
7802 opt_unexport = getopt32(argv, "!n");
7803 if (opt_unexport == (uint32_t)-1)
7804 return EXIT_FAILURE;
7805 argv += optind;
7806#else
7807 opt_unexport = 0;
7808 argv++;
7809#endif
7810
7811 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007812 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007813 if (e) {
7814 while (*e) {
7815#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007816 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007817#else
7818 /* ash emits: export VAR='VAL'
7819 * bash: declare -x VAR="VAL"
7820 * we follow ash example */
7821 const char *s = *e++;
7822 const char *p = strchr(s, '=');
7823
7824 if (!p) /* wtf? take next variable */
7825 continue;
7826 /* export var= */
7827 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007828 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007829 putchar('\n');
7830#endif
7831 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007832 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007833 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007834 return EXIT_SUCCESS;
7835 }
7836
Denys Vlasenko295fef82009-06-03 12:47:26 +02007837 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007838
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007839 return EXIT_SUCCESS;
7840}
7841
Denys Vlasenko295fef82009-06-03 12:47:26 +02007842#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007843static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007844{
7845 if (G.func_nest_level == 0) {
7846 bb_error_msg("%s: not in a function", argv[0]);
7847 return EXIT_FAILURE; /* bash compat */
7848 }
7849 helper_export_local(argv, 0, G.func_nest_level);
7850 return EXIT_SUCCESS;
7851}
7852#endif
7853
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007854static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007855{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007856 int sig;
7857 char *new_cmd;
7858
7859 if (!G.traps)
7860 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7861
7862 argv++;
7863 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007864 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007865 /* No args: print all trapped */
7866 for (i = 0; i < NSIG; ++i) {
7867 if (G.traps[i]) {
7868 printf("trap -- ");
7869 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007870 /* note: bash adds "SIG", but only if invoked
7871 * as "bash". If called as "sh", or if set -o posix,
7872 * then it prints short signal names.
7873 * We are printing short names: */
7874 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007875 }
7876 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007877 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007878 return EXIT_SUCCESS;
7879 }
7880
7881 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007882 /* If first arg is a number: reset all specified signals */
7883 sig = bb_strtou(*argv, NULL, 10);
7884 if (errno == 0) {
7885 int ret;
7886 process_sig_list:
7887 ret = EXIT_SUCCESS;
7888 while (*argv) {
7889 sig = get_signum(*argv++);
7890 if (sig < 0 || sig >= NSIG) {
7891 ret = EXIT_FAILURE;
7892 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007893 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007894 continue;
7895 }
7896
7897 free(G.traps[sig]);
7898 G.traps[sig] = xstrdup(new_cmd);
7899
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007900 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007901 get_signame(sig), sig, G.traps[sig]);
7902
7903 /* There is no signal for 0 (EXIT) */
7904 if (sig == 0)
7905 continue;
7906
7907 if (new_cmd) {
7908 sigaddset(&G.blocked_set, sig);
7909 } else {
7910 /* There was a trap handler, we are removing it
7911 * (if sig has non-DFL handling,
7912 * we don't need to do anything) */
7913 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7914 continue;
7915 sigdelset(&G.blocked_set, sig);
7916 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007917 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007918 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007919 return ret;
7920 }
7921
7922 if (!argv[1]) { /* no second arg */
7923 bb_error_msg("trap: invalid arguments");
7924 return EXIT_FAILURE;
7925 }
7926
7927 /* First arg is "-": reset all specified to default */
7928 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7929 /* Everything else: set arg as signal handler
7930 * (includes "" case, which ignores signal) */
7931 if (argv[0][0] == '-') {
7932 if (argv[0][1] == '\0') { /* "-" */
7933 /* new_cmd remains NULL: "reset these sigs" */
7934 goto reset_traps;
7935 }
7936 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7937 argv++;
7938 }
7939 /* else: "-something", no special meaning */
7940 }
7941 new_cmd = *argv;
7942 reset_traps:
7943 argv++;
7944 goto process_sig_list;
7945}
7946
Mike Frysinger93cadc22009-05-27 17:06:25 -04007947/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007948static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007949{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007950 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007951
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007952 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007953 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007954 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007955
7956 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007957 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007958 type = "an alias";*/
7959#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007960 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007961 type = "a function";
7962#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007963 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007964 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007965 else if ((path = find_in_path(*argv)) != NULL)
7966 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007967 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007968 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007969 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007970 continue;
7971 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007972
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007973 printf("%s is %s\n", *argv, type);
7974 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007975 }
7976
7977 return ret;
7978}
7979
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007980#if ENABLE_HUSH_JOB
7981/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007982static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007983{
7984 int i, jobnum;
7985 struct pipe *pi;
7986
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007987 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007988 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007989
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007990 /* If they gave us no args, assume they want the last backgrounded task */
7991 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007992 for (pi = G.job_list; pi; pi = pi->next) {
7993 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007994 goto found;
7995 }
7996 }
7997 bb_error_msg("%s: no current job", argv[0]);
7998 return EXIT_FAILURE;
7999 }
8000 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8001 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8002 return EXIT_FAILURE;
8003 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008004 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008005 if (pi->jobid == jobnum) {
8006 goto found;
8007 }
8008 }
8009 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8010 return EXIT_FAILURE;
8011 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008012 /* TODO: bash prints a string representation
8013 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008014 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008015 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008016 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008017 }
8018
8019 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008020 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8021 for (i = 0; i < pi->num_cmds; i++) {
8022 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8023 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008024 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008025 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008026
8027 i = kill(- pi->pgrp, SIGCONT);
8028 if (i < 0) {
8029 if (errno == ESRCH) {
8030 delete_finished_bg_job(pi);
8031 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008032 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008033 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008034 }
8035
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008036 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008037 remove_bg_job(pi);
8038 return checkjobs_and_fg_shell(pi);
8039 }
8040 return EXIT_SUCCESS;
8041}
8042#endif
8043
8044#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008045static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008046{
8047 const struct built_in_command *x;
8048
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008049 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008050 "Built-in commands:\n"
8051 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008052 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008053 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008054 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008055 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008056 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008057 return EXIT_SUCCESS;
8058}
8059#endif
8060
8061#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008062static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008063{
8064 struct pipe *job;
8065 const char *status_string;
8066
Denis Vlasenko87a86552008-07-29 19:43:10 +00008067 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008068 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008069 status_string = "Stopped";
8070 else
8071 status_string = "Running";
8072
8073 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8074 }
8075 return EXIT_SUCCESS;
8076}
8077#endif
8078
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008079#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008080static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008081{
8082 void *p;
8083 unsigned long l;
8084
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008085# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008086 /* Optional. Reduces probability of false positives */
8087 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008088# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008089 /* Crude attempt to find where "free memory" starts,
8090 * sans fragmentation. */
8091 p = malloc(240);
8092 l = (unsigned long)p;
8093 free(p);
8094 p = malloc(3400);
8095 if (l < (unsigned long)p) l = (unsigned long)p;
8096 free(p);
8097
8098 if (!G.memleak_value)
8099 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008100
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008101 l -= G.memleak_value;
8102 if ((long)l < 0)
8103 l = 0;
8104 l /= 1024;
8105 if (l > 127)
8106 l = 127;
8107
8108 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8109 return l;
8110}
8111#endif
8112
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008113static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008114{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008115 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008116 return EXIT_SUCCESS;
8117}
8118
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008119static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008120{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008121 const char *r;
8122 char *opt_n = NULL;
8123 char *opt_p = NULL;
8124 char *opt_t = NULL;
8125 char *opt_u = NULL;
8126 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008127
Denys Vlasenko03dad222010-01-12 23:29:57 +01008128 /* "!": do not abort on errors.
8129 * Option string must start with "sr" to match BUILTIN_READ_xxx
8130 */
8131 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8132 if (read_flags == (uint32_t)-1)
8133 return EXIT_FAILURE;
8134 argv += optind;
8135
8136 r = shell_builtin_read(set_local_var_from_halves,
8137 argv,
8138 get_local_var_value("IFS"), /* can be NULL */
8139 read_flags,
8140 opt_n,
8141 opt_p,
8142 opt_t,
8143 opt_u
8144 );
8145
8146 if ((uintptr_t)r > 1) {
8147 bb_error_msg("%s", r);
8148 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008149 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008150
Denys Vlasenko03dad222010-01-12 23:29:57 +01008151 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008152}
8153
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008154/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8155 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008156 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008157 * set [-abCefhmnuvx] [-o option] [argument...]
8158 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008159 * set -- [argument...]
8160 * set -o
8161 * set +o
8162 * Implementations shall support the options in both their hyphen and
8163 * plus-sign forms. These options can also be specified as options to sh.
8164 * Examples:
8165 * Write out all variables and their values: set
8166 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8167 * Turn on the -x and -v options: set -xv
8168 * Unset all positional parameters: set --
8169 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8170 * Set the positional parameters to the expansion of x, even if x expands
8171 * with a leading '-' or '+': set -- $x
8172 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008173 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008174 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008175static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008176{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008177 int n;
8178 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008179 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008180
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008181 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008182 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008183 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008184 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008185 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008186 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008187
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008188 do {
8189 if (!strcmp(arg, "--")) {
8190 ++argv;
8191 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008192 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008193 if (arg[0] != '+' && arg[0] != '-')
8194 break;
8195 for (n = 1; arg[n]; ++n)
8196 if (set_mode(arg[0], arg[n]))
8197 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008198 } while ((arg = *++argv) != NULL);
8199 /* Now argv[0] is 1st argument */
8200
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008201 if (arg == NULL)
8202 return EXIT_SUCCESS;
8203 set_argv:
8204
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008205 /* NB: G.global_argv[0] ($0) is never freed/changed */
8206 g_argv = G.global_argv;
8207 if (G.global_args_malloced) {
8208 pp = g_argv;
8209 while (*++pp)
8210 free(*pp);
8211 g_argv[1] = NULL;
8212 } else {
8213 G.global_args_malloced = 1;
8214 pp = xzalloc(sizeof(pp[0]) * 2);
8215 pp[0] = g_argv[0]; /* retain $0 */
8216 g_argv = pp;
8217 }
8218 /* This realloc's G.global_argv */
8219 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8220
8221 n = 1;
8222 while (*++pp)
8223 n++;
8224 G.global_argc = n;
8225
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008226 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008227
8228 /* Nothing known, so abort */
8229 error:
8230 bb_error_msg("set: %s: invalid option", arg);
8231 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008232}
8233
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008234static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008235{
8236 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008237 argv = skip_dash_dash(argv);
8238 if (argv[0]) {
8239 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008240 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008241 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008242 if (G.global_args_malloced) {
8243 int m = 1;
8244 while (m <= n)
8245 free(G.global_argv[m++]);
8246 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008247 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008248 memmove(&G.global_argv[1], &G.global_argv[n+1],
8249 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008250 return EXIT_SUCCESS;
8251 }
8252 return EXIT_FAILURE;
8253}
8254
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008255static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008256{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008257 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008258 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008259 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008260#if ENABLE_HUSH_FUNCTIONS
8261 smallint sv_flg;
8262#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008263
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008264 argv = skip_dash_dash(argv);
8265 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008266 if (!filename) {
8267 /* bash says: "bash: .: filename argument required" */
8268 return 2; /* bash compat */
8269 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008270 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008271 if (!strchr(filename, '/')) {
8272 arg_path = find_in_path(filename);
8273 if (arg_path)
8274 filename = arg_path;
8275 }
8276 input = fopen_or_warn(filename, "r");
8277 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008278 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008279 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008280 return EXIT_FAILURE;
8281 }
8282 close_on_exec_on(fileno(input));
8283
Mike Frysinger885b6f22009-04-18 21:04:25 +00008284#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008285 sv_flg = G.flag_return_in_progress;
8286 /* "we are inside sourced file, ok to use return" */
8287 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008288#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008289 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008290
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008291 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008292 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008293
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008294 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008295#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008296 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008297#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008298
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008299 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008300}
8301
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008302static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008303{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008304 int rc;
8305 mode_t mask;
8306
8307 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008308 argv = skip_dash_dash(argv);
8309 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008310 mode_t old_mask = mask;
8311
8312 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008313 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008314 mask ^= 0777;
8315 if (rc == 0) {
8316 mask = old_mask;
8317 /* bash messages:
8318 * bash: umask: 'q': invalid symbolic mode operator
8319 * bash: umask: 999: octal number out of range
8320 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008321 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008322 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008323 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008324 rc = 1;
8325 /* Mimic bash */
8326 printf("%04o\n", (unsigned) mask);
8327 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008328 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008329 umask(mask);
8330
8331 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008332}
8333
Mike Frysingerd690f682009-03-30 06:50:54 +00008334/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008335static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008336{
Mike Frysingerd690f682009-03-30 06:50:54 +00008337 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008338 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008339
Denis Vlasenko28e67962009-04-26 23:22:40 +00008340 /* "!": do not abort on errors */
8341 /* "+": stop at 1st non-option */
8342 opts = getopt32(argv, "!+vf");
8343 if (opts == (unsigned)-1)
8344 return EXIT_FAILURE;
8345 if (opts == 3) {
8346 bb_error_msg("unset: -v and -f are exclusive");
8347 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008348 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008349 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008350
8351 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008352 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008353 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008354 if (unset_local_var(*argv)) {
8355 /* unset <nonexistent_var> doesn't fail.
8356 * Error is when one tries to unset RO var.
8357 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008358 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008359 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008360 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008361#if ENABLE_HUSH_FUNCTIONS
8362 else {
8363 unset_func(*argv);
8364 }
8365#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008366 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008367 }
8368 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008369}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008370
Mike Frysinger56bdea12009-03-28 20:01:58 +00008371/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008372static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008373{
8374 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008375 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008376
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008377 argv = skip_dash_dash(argv);
8378 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008379 /* Don't care about wait results */
8380 /* Note 1: must wait until there are no more children */
8381 /* Note 2: must be interruptible */
8382 /* Examples:
8383 * $ sleep 3 & sleep 6 & wait
8384 * [1] 30934 sleep 3
8385 * [2] 30935 sleep 6
8386 * [1] Done sleep 3
8387 * [2] Done sleep 6
8388 * $ sleep 3 & sleep 6 & wait
8389 * [1] 30936 sleep 3
8390 * [2] 30937 sleep 6
8391 * [1] Done sleep 3
8392 * ^C <-- after ~4 sec from keyboard
8393 * $
8394 */
8395 sigaddset(&G.blocked_set, SIGCHLD);
8396 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8397 while (1) {
8398 checkjobs(NULL);
8399 if (errno == ECHILD)
8400 break;
8401 /* Wait for SIGCHLD or any other signal of interest */
8402 /* sigtimedwait with infinite timeout: */
8403 sig = sigwaitinfo(&G.blocked_set, NULL);
8404 if (sig > 0) {
8405 sig = check_and_run_traps(sig);
8406 if (sig && sig != SIGCHLD) { /* see note 2 */
8407 ret = 128 + sig;
8408 break;
8409 }
8410 }
8411 }
8412 sigdelset(&G.blocked_set, SIGCHLD);
8413 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8414 return ret;
8415 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008416
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008417 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008418 while (*argv) {
8419 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008420 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008421 /* mimic bash message */
8422 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008423 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008424 }
8425 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008426 if (WIFSIGNALED(status))
8427 ret = 128 + WTERMSIG(status);
8428 else if (WIFEXITED(status))
8429 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008430 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008431 ret = EXIT_FAILURE;
8432 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008433 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008434 ret = 127;
8435 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008436 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008437 }
8438
8439 return ret;
8440}
8441
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008442#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8443static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8444{
8445 if (argv[1]) {
8446 def = bb_strtou(argv[1], NULL, 10);
8447 if (errno || def < def_min || argv[2]) {
8448 bb_error_msg("%s: bad arguments", argv[0]);
8449 def = UINT_MAX;
8450 }
8451 }
8452 return def;
8453}
8454#endif
8455
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008456#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008457static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008458{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008459 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008460 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008461 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008462 return EXIT_SUCCESS; /* bash compat */
8463 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008464 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008465
8466 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8467 if (depth == UINT_MAX)
8468 G.flag_break_continue = BC_BREAK;
8469 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008470 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008471
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008472 return EXIT_SUCCESS;
8473}
8474
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008475static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008476{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008477 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8478 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008479}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008480#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008481
8482#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008483static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008484{
8485 int rc;
8486
8487 if (G.flag_return_in_progress != -1) {
8488 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8489 return EXIT_FAILURE; /* bash compat */
8490 }
8491
8492 G.flag_return_in_progress = 1;
8493
8494 /* bash:
8495 * out of range: wraps around at 256, does not error out
8496 * non-numeric param:
8497 * f() { false; return qwe; }; f; echo $?
8498 * bash: return: qwe: numeric argument required <== we do this
8499 * 255 <== we also do this
8500 */
8501 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8502 return rc;
8503}
8504#endif