blob: c67aebdd75daa21621b09813ba0f4a9f7a35138f [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
117//config: hush is a small shell (22k). It handles the normal flow control
118//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
224//config: This instructs hush to print commands before execution. Adds ~300 bytes.
225//config:
226
227//usage:#define hush_trivial_usage NOUSAGE_STR
228//usage:#define hush_full_usage ""
229//usage:#define lash_trivial_usage NOUSAGE_STR
230//usage:#define lash_full_usage ""
231//usage:#define msh_trivial_usage NOUSAGE_STR
232//usage:#define msh_full_usage ""
233
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000234
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200235/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000236#define LEAK_HUNTING 0
237#define BUILD_AS_NOMMU 0
238/* Enable/disable sanity checks. Ok to enable in production,
239 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
240 * Keeping 1 for now even in released versions.
241 */
242#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200243/* Slightly bigger (+200 bytes), but faster hush.
244 * So far it only enables a trick with counting SIGCHLDs and forks,
245 * which allows us to do fewer waitpid's.
246 * (we can detect a case where neither forks were done nor SIGCHLDs happened
247 * and therefore waitpid will return the same result as last time)
248 */
249#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200250/* TODO: implement simplified code for users which do not need ${var%...} ops
251 * So far ${var%...} ops are always enabled:
252 */
253#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000254
255
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000256#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000257# undef BB_MMU
258# undef USE_FOR_NOMMU
259# undef USE_FOR_MMU
260# define BB_MMU 0
261# define USE_FOR_NOMMU(...) __VA_ARGS__
262# define USE_FOR_MMU(...)
263#endif
264
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200265#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100266#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000267/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000268# undef CONFIG_FEATURE_SH_STANDALONE
269# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000270# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100271# undef IF_NOT_FEATURE_SH_STANDALONE
272# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000273# define IF_FEATURE_SH_STANDALONE(...)
274# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000275#endif
276
Denis Vlasenko05743d72008-02-10 12:10:08 +0000277#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000278# undef ENABLE_FEATURE_EDITING
279# define ENABLE_FEATURE_EDITING 0
280# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
281# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000282#endif
283
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000284/* Do we support ANY keywords? */
285#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000286# define HAS_KEYWORDS 1
287# define IF_HAS_KEYWORDS(...) __VA_ARGS__
288# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000289#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000290# define HAS_KEYWORDS 0
291# define IF_HAS_KEYWORDS(...)
292# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000293#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000294
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000295/* If you comment out one of these below, it will be #defined later
296 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000297#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000298/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000299#define debug_printf_parse(...) do {} while (0)
300#define debug_print_tree(a, b) do {} while (0)
301#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000302#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000303#define debug_printf_jobs(...) do {} while (0)
304#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200305#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000306#define debug_printf_glob(...) do {} while (0)
307#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000308#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000309#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000310
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000311#define ERR_PTR ((void*)(long)1)
312
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200313#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000314
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200315#define _SPECIAL_VARS_STR "_*@$!?#"
316#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
317#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
318
319#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000320
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200321struct variable;
322
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000323static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
324
325/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000326 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000327 */
328#if !BB_MMU
329typedef struct nommu_save_t {
330 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200331 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000332 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000333 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000334} nommu_save_t;
335#endif
336
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000337typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000338 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000339#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000340 RES_IF ,
341 RES_THEN ,
342 RES_ELIF ,
343 RES_ELSE ,
344 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000345#endif
346#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000347 RES_FOR ,
348 RES_WHILE ,
349 RES_UNTIL ,
350 RES_DO ,
351 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000352#endif
353#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000354 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000355#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000356#if ENABLE_HUSH_CASE
357 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200358 /* three pseudo-keywords support contrived "case" syntax: */
359 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
360 RES_MATCH , /* "word)" */
361 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000362 RES_ESAC ,
363#endif
364 RES_XXXX ,
365 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000366} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000367
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000368typedef struct o_string {
369 char *data;
370 int length; /* position where data is appended */
371 int maxlen;
372 /* Protect newly added chars against globbing
373 * (by prepending \ to *, ?, [, \) */
374 smallint o_escape;
375 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000376 /* At least some part of the string was inside '' or "",
377 * possibly empty one: word"", wo''rd etc. */
378 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000379 smallint has_empty_slot;
380 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
381} o_string;
382enum {
383 MAYBE_ASSIGNMENT = 0,
384 DEFINITELY_ASSIGNMENT = 1,
385 NOT_ASSIGNMENT = 2,
386 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
387};
388/* Used for initialization: o_string foo = NULL_O_STRING; */
389#define NULL_O_STRING { NULL }
390
391/* I can almost use ordinary FILE*. Is open_memstream() universally
392 * available? Where is it documented? */
393typedef struct in_str {
394 const char *p;
395 /* eof_flag=1: last char in ->p is really an EOF */
396 char eof_flag; /* meaningless if ->p == NULL */
397 char peek_buf[2];
398#if ENABLE_HUSH_INTERACTIVE
399 smallint promptme;
400 smallint promptmode; /* 0: PS1, 1: PS2 */
401#endif
402 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200403 int (*get) (struct in_str *) FAST_FUNC;
404 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000405} in_str;
406#define i_getch(input) ((input)->get(input))
407#define i_peek(input) ((input)->peek(input))
408
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200409/* The descrip member of this structure is only used to make
410 * debugging output pretty */
411static const struct {
412 int mode;
413 signed char default_fd;
414 char descrip[3];
415} redir_table[] = {
416 { O_RDONLY, 0, "<" },
417 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
418 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
419 { O_CREAT|O_RDWR, 1, "<>" },
420 { O_RDONLY, 0, "<<" },
421/* Should not be needed. Bogus default_fd helps in debugging */
422/* { O_RDONLY, 77, "<<" }, */
423};
424
Eric Andersen25f27032001-04-26 23:22:31 +0000425struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000426 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000427 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000428 int rd_fd; /* fd to redirect */
429 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
430 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000431 smallint rd_type; /* (enum redir_type) */
432 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000433 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200434 * bit 0: do we need to trim leading tabs?
435 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000436 */
Eric Andersen25f27032001-04-26 23:22:31 +0000437};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000438typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200439 REDIRECT_INPUT = 0,
440 REDIRECT_OVERWRITE = 1,
441 REDIRECT_APPEND = 2,
442 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000443 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200444 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000445
446 REDIRFD_CLOSE = -3,
447 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000448 REDIRFD_TO_FILE = -1,
449 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000450
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000451 HEREDOC_SKIPTABS = 1,
452 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000453} redir_type;
454
Eric Andersen25f27032001-04-26 23:22:31 +0000455
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000456struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000457 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000458 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000459 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200460 smallint cmd_type; /* CMD_xxx */
461#define CMD_NORMAL 0
462#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200463
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200464/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200465#if ENABLE_HUSH_BASH_COMPAT
466# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000467#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200468
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200469/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200470//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200471// It is hard to implement correctly, it adds significant amounts of tricky code,
472// and all this is only useful for really obscure export statements
473// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
474// guards the code which implements it, but I have doubts it works
475// in all cases (especially with mixed globbed/non-globbed arguments)
476
477#if ENABLE_HUSH_FUNCTIONS
478# define CMD_FUNCDEF 3
479#endif
480
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200481 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
482 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000483#if !BB_MMU
484 char *group_as_string;
485#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000486#if ENABLE_HUSH_FUNCTIONS
487 struct function *child_func;
488/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200489 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000490 * When we execute "f1() {a;}" cmd, we create new function and clear
491 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200492 * When we execute "f1() {b;}", we notice that f1 exists,
493 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000494 * we put those fields back into cmd->xxx
495 * (struct function has ->parent_cmd ptr to facilitate that).
496 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
497 * Without this trick, loop would execute a;b;b;b;...
498 * instead of correct sequence a;b;a;b;...
499 * When command is freed, it severs the link
500 * (sets ->child_func->parent_cmd to NULL).
501 */
502#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000503 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000504/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
505 * and on execution these are substituted with their values.
506 * Substitution can make _several_ words out of one argv[n]!
507 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000508 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000509 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000510 struct redir_struct *redirects; /* I/O redirections */
511};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000512/* Is there anything in this command at all? */
513#define IS_NULL_CMD(cmd) \
514 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
515
Eric Andersen25f27032001-04-26 23:22:31 +0000516
517struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000518 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000519 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000520 int alive_cmds; /* number of commands running (not exited) */
521 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000522#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000523 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000524 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000525 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000526#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000527 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000528 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000529 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
530 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000531};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000532typedef enum pipe_style {
533 PIPE_SEQ = 1,
534 PIPE_AND = 2,
535 PIPE_OR = 3,
536 PIPE_BG = 4,
537} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000538/* Is there anything in this pipe at all? */
539#define IS_NULL_PIPE(pi) \
540 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000541
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000542/* This holds pointers to the various results of parsing */
543struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000544 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000545 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000546 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000547 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000548 /* last command in pipe (being constructed right now) */
549 struct command *command;
550 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000551 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000552#if !BB_MMU
553 o_string as_string;
554#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000555#if HAS_KEYWORDS
556 smallint ctx_res_w;
557 smallint ctx_inverted; /* "! cmd | cmd" */
558#if ENABLE_HUSH_CASE
559 smallint ctx_dsemicolon; /* ";;" seen */
560#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000561 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
562 int old_flag;
563 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000564 * example: "if pipe1; pipe2; then pipe3; fi"
565 * when we see "if" or "then", we malloc and copy current context,
566 * and make ->stack point to it. then we parse pipeN.
567 * when closing "then" / fi" / whatever is found,
568 * we move list_head into ->stack->command->group,
569 * copy ->stack into current context, and delete ->stack.
570 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000571 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000572 struct parse_context *stack;
573#endif
574};
575
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000576/* On program start, environ points to initial environment.
577 * putenv adds new pointers into it, unsetenv removes them.
578 * Neither of these (de)allocates the strings.
579 * setenv allocates new strings in malloc space and does putenv,
580 * and thus setenv is unusable (leaky) for shell's purposes */
581#define setenv(...) setenv_is_leaky_dont_use()
582struct variable {
583 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000584 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200585#if ENABLE_HUSH_LOCAL
586 unsigned func_nest_level;
587#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000588 int max_len; /* if > 0, name is part of initial env; else name is malloced */
589 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000590 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000591};
592
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000593enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000594 BC_BREAK = 1,
595 BC_CONTINUE = 2,
596};
597
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000598#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000599struct function {
600 struct function *next;
601 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000602 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000603 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200604# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000605 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200606# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000607};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000608#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000609
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000610
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000611/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000612/* Sorted roughly by size (smaller offsets == smaller code) */
613struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000614 /* interactive_fd != 0 means we are an interactive shell.
615 * If we are, then saved_tty_pgrp can also be != 0, meaning
616 * that controlling tty is available. With saved_tty_pgrp == 0,
617 * job control still works, but terminal signals
618 * (^C, ^Z, ^Y, ^\) won't work at all, and background
619 * process groups can only be created with "cmd &".
620 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
621 * to give tty to the foreground process group,
622 * and will take it back when the group is stopped (^Z)
623 * or killed (^C).
624 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000625#if ENABLE_HUSH_INTERACTIVE
626 /* 'interactive_fd' is a fd# open to ctty, if we have one
627 * _AND_ if we decided to act interactively */
628 int interactive_fd;
629 const char *PS1;
630 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000631# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000632#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000633# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000634#endif
635#if ENABLE_FEATURE_EDITING
636 line_input_t *line_input_state;
637#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000638 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200639 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000640 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200641#if ENABLE_HUSH_RANDOM_SUPPORT
642 random_t random_gen;
643#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000644#if ENABLE_HUSH_JOB
645 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000646 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000647 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000648 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400649# define G_saved_tty_pgrp (G.saved_tty_pgrp)
650#else
651# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000652#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000653 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000654#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000655 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000656#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000657#if ENABLE_HUSH_FUNCTIONS
658 /* 0: outside of a function (or sourced file)
659 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000660 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000661 */
662 smallint flag_return_in_progress;
663#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200664 smallint n_mode;
665#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200666 smallint x_mode;
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200667# define G_x_mode G.x_mode
668#else
669# define G_x_mode 0
670#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000671 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000672 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000673 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000674 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000675 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100676 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000677 /* how many non-NULL argv's we have. NB: $# + 1 */
678 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000679 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000680#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000681 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000682#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000683#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000684 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000685 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000686#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000687 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000688 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000689 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000690 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000691#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000692 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200693# if ENABLE_HUSH_LOCAL
694 struct variable **shadowed_vars_pp;
695 unsigned func_nest_level;
696# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000697#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000698 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200699#if ENABLE_HUSH_FAST
700 unsigned count_SIGCHLD;
701 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200702 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200703#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000704 /* which signals have non-DFL handler (even with no traps set)? */
705 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000706 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000707 sigset_t blocked_set;
708 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000709#if HUSH_DEBUG
710 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000711 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000712#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200713 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000714};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000715#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000716/* Not #defining name to G.name - this quickly gets unwieldy
717 * (too many defines). Also, I actually prefer to see when a variable
718 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000719#define INIT_G() do { \
720 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
721} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000722
723
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000724/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200725static int builtin_cd(char **argv) FAST_FUNC;
726static int builtin_echo(char **argv) FAST_FUNC;
727static int builtin_eval(char **argv) FAST_FUNC;
728static int builtin_exec(char **argv) FAST_FUNC;
729static int builtin_exit(char **argv) FAST_FUNC;
730static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000731#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200732static int builtin_fg_bg(char **argv) FAST_FUNC;
733static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000734#endif
735#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200736static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000737#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200738#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200739static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200740#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000741#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200742static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000743#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400744#if ENABLE_PRINTF
745static int builtin_printf(char **argv) FAST_FUNC;
746#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200747static int builtin_pwd(char **argv) FAST_FUNC;
748static int builtin_read(char **argv) FAST_FUNC;
749static int builtin_set(char **argv) FAST_FUNC;
750static int builtin_shift(char **argv) FAST_FUNC;
751static int builtin_source(char **argv) FAST_FUNC;
752static int builtin_test(char **argv) FAST_FUNC;
753static int builtin_trap(char **argv) FAST_FUNC;
754static int builtin_type(char **argv) FAST_FUNC;
755static int builtin_true(char **argv) FAST_FUNC;
756static int builtin_umask(char **argv) FAST_FUNC;
757static int builtin_unset(char **argv) FAST_FUNC;
758static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000759#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200760static int builtin_break(char **argv) FAST_FUNC;
761static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000762#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000763#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200764static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000765#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000766
767/* Table of built-in functions. They can be forked or not, depending on
768 * context: within pipes, they fork. As simple commands, they do not.
769 * When used in non-forking context, they can change global variables
770 * in the parent shell process. If forked, of course they cannot.
771 * For example, 'unset foo | whatever' will parse and run, but foo will
772 * still be set at the end. */
773struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100774 const char *b_cmd;
775 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000776#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100777 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200778# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000779#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200780# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000781#endif
782};
783
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200784static const struct built_in_command bltins1[] = {
785 BLTIN("." , builtin_source , "Run commands in a file"),
786 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000787#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200788 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000789#endif
790#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200791 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000792#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200793 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000794#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200795 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000796#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200797 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
798 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
799 BLTIN("exit" , builtin_exit , "Exit"),
800 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000801#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200802 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000803#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000804#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200805 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000806#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000807#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200808 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000809#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200810#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200811 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200812#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000813#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200814 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000815#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200816 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000817#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200818 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000819#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200820 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
821 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200822#if ENABLE_HUSH_BASH_COMPAT
823 BLTIN("source" , builtin_source , "Run commands in a file"),
824#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200825 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100826 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100827 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200828 BLTIN("umask" , builtin_umask , "Set file creation mask"),
829 BLTIN("unset" , builtin_unset , "Unset variables"),
830 BLTIN("wait" , builtin_wait , "Wait for process"),
831};
832/* For now, echo and test are unconditionally enabled.
833 * Maybe make it configurable? */
834static const struct built_in_command bltins2[] = {
835 BLTIN("[" , builtin_test , NULL),
836 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400837#if ENABLE_PRINTF
838 BLTIN("printf" , builtin_printf , NULL),
839#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200840 BLTIN("pwd" , builtin_pwd , NULL),
841 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000842};
843
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000844
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000845/* Debug printouts.
846 */
847#if HUSH_DEBUG
848/* prevent disasters with G.debug_indent < 0 */
849# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
850# define debug_enter() (G.debug_indent++)
851# define debug_leave() (G.debug_indent--)
852#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200853# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000854# define debug_enter() ((void)0)
855# define debug_leave() ((void)0)
856#endif
857
858#ifndef debug_printf
859# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
860#endif
861
862#ifndef debug_printf_parse
863# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
864#endif
865
866#ifndef debug_printf_exec
867#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
868#endif
869
870#ifndef debug_printf_env
871# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
872#endif
873
874#ifndef debug_printf_jobs
875# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
876# define DEBUG_JOBS 1
877#else
878# define DEBUG_JOBS 0
879#endif
880
881#ifndef debug_printf_expand
882# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
883# define DEBUG_EXPAND 1
884#else
885# define DEBUG_EXPAND 0
886#endif
887
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200888#ifndef debug_printf_varexp
889# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
890#endif
891
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000892#ifndef debug_printf_glob
893# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
894# define DEBUG_GLOB 1
895#else
896# define DEBUG_GLOB 0
897#endif
898
899#ifndef debug_printf_list
900# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
901#endif
902
903#ifndef debug_printf_subst
904# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
905#endif
906
907#ifndef debug_printf_clean
908# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
909# define DEBUG_CLEAN 1
910#else
911# define DEBUG_CLEAN 0
912#endif
913
914#if DEBUG_EXPAND
915static void debug_print_strings(const char *prefix, char **vv)
916{
917 indent();
918 fprintf(stderr, "%s:\n", prefix);
919 while (*vv)
920 fprintf(stderr, " '%s'\n", *vv++);
921}
922#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200923# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000924#endif
925
926
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000927/* Leak hunting. Use hush_leaktool.sh for post-processing.
928 */
929#if LEAK_HUNTING
930static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000931{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000932 void *ptr = xmalloc((size + 0xff) & ~0xff);
933 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
934 return ptr;
935}
936static void *xxrealloc(int lineno, void *ptr, size_t size)
937{
938 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
939 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
940 return ptr;
941}
942static char *xxstrdup(int lineno, const char *str)
943{
944 char *ptr = xstrdup(str);
945 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
946 return ptr;
947}
948static void xxfree(void *ptr)
949{
950 fdprintf(2, "free %p\n", ptr);
951 free(ptr);
952}
Denys Vlasenko8391c482010-05-22 17:50:43 +0200953# define xmalloc(s) xxmalloc(__LINE__, s)
954# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
955# define xstrdup(s) xxstrdup(__LINE__, s)
956# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000957#endif
958
959
960/* Syntax and runtime errors. They always abort scripts.
961 * In interactive use they usually discard unparsed and/or unexecuted commands
962 * and return to the prompt.
963 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
964 */
965#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200966# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000967# define syntax_error(lineno, msg) syntax_error(msg)
968# define syntax_error_at(lineno, msg) syntax_error_at(msg)
969# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
970# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
971# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000972#endif
973
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000974static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000975{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000976 va_list p;
977
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000978#if HUSH_DEBUG >= 2
979 bb_error_msg("hush.c:%u", lineno);
980#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000981 va_start(p, fmt);
982 bb_verror_msg(fmt, p, NULL);
983 va_end(p);
984 if (!G_interactive_fd)
985 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000986}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000987
988static void syntax_error(unsigned lineno, const char *msg)
989{
990 if (msg)
991 die_if_script(lineno, "syntax error: %s", msg);
992 else
993 die_if_script(lineno, "syntax error", NULL);
994}
995
996static void syntax_error_at(unsigned lineno, const char *msg)
997{
998 die_if_script(lineno, "syntax error at '%s'", msg);
999}
1000
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001001static void syntax_error_unterm_str(unsigned lineno, const char *s)
1002{
1003 die_if_script(lineno, "syntax error: unterminated %s", s);
1004}
1005
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001006/* It so happens that all such cases are totally fatal
1007 * even if shell is interactive: EOF while looking for closing
1008 * delimiter. There is nowhere to read stuff from after that,
1009 * it's EOF! The only choice is to terminate.
1010 */
1011static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001012static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001013{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001014 char msg[2] = { ch, '\0' };
1015 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001016 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001017}
1018
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001019static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001020{
1021 char msg[2];
1022 msg[0] = ch;
1023 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001024 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001025}
1026
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001027#if HUSH_DEBUG < 2
1028# undef die_if_script
1029# undef syntax_error
1030# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001031# undef syntax_error_unterm_ch
1032# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001033# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001034#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001035# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001036# define syntax_error(msg) syntax_error(__LINE__, msg)
1037# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1038# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1039# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1040# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001041#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001042
Denis Vlasenko552433b2009-04-04 19:29:21 +00001043
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001044#if ENABLE_HUSH_INTERACTIVE
1045static void cmdedit_update_prompt(void);
1046#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001047# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001048#endif
1049
1050
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001051/* Utility functions
1052 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001053/* Replace each \x with x in place, return ptr past NUL. */
1054static char *unbackslash(char *src)
1055{
Denys Vlasenko71885402009-09-24 01:44:13 +02001056 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001057 while (1) {
1058 if (*src == '\\')
1059 src++;
1060 if ((*dst++ = *src++) == '\0')
1061 break;
1062 }
1063 return dst;
1064}
1065
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001066static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001067{
1068 int i;
1069 unsigned count1;
1070 unsigned count2;
1071 char **v;
1072
1073 v = strings;
1074 count1 = 0;
1075 if (v) {
1076 while (*v) {
1077 count1++;
1078 v++;
1079 }
1080 }
1081 count2 = 0;
1082 v = add;
1083 while (*v) {
1084 count2++;
1085 v++;
1086 }
1087 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1088 v[count1 + count2] = NULL;
1089 i = count2;
1090 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001091 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001092 return v;
1093}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001094#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001095static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1096{
1097 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1098 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1099 return ptr;
1100}
1101#define add_strings_to_strings(strings, add, need_to_dup) \
1102 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1103#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001104
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001105/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001106static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001107{
1108 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001109 v[0] = add;
1110 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001111 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001112}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001113#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001114static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1115{
1116 char **ptr = add_string_to_strings(strings, add);
1117 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1118 return ptr;
1119}
1120#define add_string_to_strings(strings, add) \
1121 xx_add_string_to_strings(__LINE__, strings, add)
1122#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001123
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001124static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001125{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001126 char **v;
1127
1128 if (!strings)
1129 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001130 v = strings;
1131 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001132 free(*v);
1133 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001134 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001135 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001136}
1137
Denis Vlasenko76d50412008-06-10 16:19:39 +00001138
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001139/* Helpers for setting new $n and restoring them back
1140 */
1141typedef struct save_arg_t {
1142 char *sv_argv0;
1143 char **sv_g_argv;
1144 int sv_g_argc;
1145 smallint sv_g_malloced;
1146} save_arg_t;
1147
1148static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1149{
1150 int n;
1151
1152 sv->sv_argv0 = argv[0];
1153 sv->sv_g_argv = G.global_argv;
1154 sv->sv_g_argc = G.global_argc;
1155 sv->sv_g_malloced = G.global_args_malloced;
1156
1157 argv[0] = G.global_argv[0]; /* retain $0 */
1158 G.global_argv = argv;
1159 G.global_args_malloced = 0;
1160
1161 n = 1;
1162 while (*++argv)
1163 n++;
1164 G.global_argc = n;
1165}
1166
1167static void restore_G_args(save_arg_t *sv, char **argv)
1168{
1169 char **pp;
1170
1171 if (G.global_args_malloced) {
1172 /* someone ran "set -- arg1 arg2 ...", undo */
1173 pp = G.global_argv;
1174 while (*++pp) /* note: does not free $0 */
1175 free(*pp);
1176 free(G.global_argv);
1177 }
1178 argv[0] = sv->sv_argv0;
1179 G.global_argv = sv->sv_g_argv;
1180 G.global_argc = sv->sv_g_argc;
1181 G.global_args_malloced = sv->sv_g_malloced;
1182}
1183
1184
Denis Vlasenkod5762932009-03-31 11:22:57 +00001185/* Basic theory of signal handling in shell
1186 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001187 * This does not describe what hush does, rather, it is current understanding
1188 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001189 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1190 *
1191 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1192 * is finished or backgrounded. It is the same in interactive and
1193 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001194 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001195 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001196 * backgrounds (i.e. stops) or kills all members of currently running
1197 * pipe.
1198 *
1199 * Wait builtin in interruptible by signals for which user trap is set
1200 * or by SIGINT in interactive shell.
1201 *
1202 * Trap handlers will execute even within trap handlers. (right?)
1203 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001204 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1205 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001206 *
1207 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001208 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001209 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001210 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001211 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001212 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001213 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001214 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001215 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001216 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001217 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001218 *
1219 * SIGQUIT: ignore
1220 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001221 * SIGHUP (interactive):
1222 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001223 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001224 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1225 * that all pipe members are stopped. Try this in bash:
1226 * while :; do :; done - ^Z does not background it
1227 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001228 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001229 * of the command line, show prompt. NB: ^C does not send SIGINT
1230 * to interactive shell while shell is waiting for a pipe,
1231 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001232 * Example 1: this waits 5 sec, but does not execute ls:
1233 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1234 * Example 2: this does not wait and does not execute ls:
1235 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1236 * Example 3: this does not wait 5 sec, but executes ls:
1237 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001238 *
1239 * (What happens to signals which are IGN on shell start?)
1240 * (What happens with signal mask on shell start?)
1241 *
1242 * Implementation in hush
1243 * ======================
1244 * We use in-kernel pending signal mask to determine which signals were sent.
1245 * We block all signals which we don't want to take action immediately,
1246 * i.e. we block all signals which need to have special handling as described
1247 * above, and all signals which have traps set.
1248 * After each pipe execution, we extract any pending signals via sigtimedwait()
1249 * and act on them.
1250 *
1251 * unsigned non_DFL_mask: a mask of such "special" signals
1252 * sigset_t blocked_set: current blocked signal set
1253 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001254 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001255 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001256 * "trap 'cmd' SIGxxx":
1257 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001258 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001259 * unblock signals with special interactive handling
1260 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001261 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001262 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001263 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001264 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001265 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001266 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001267 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001268 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001269 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001270 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001271 * Standard says "When a subshell is entered, traps that are not being ignored
1272 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001273 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001274 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001275enum {
1276 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001277 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001278 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001279 | (1 << SIGHUP)
1280 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001281 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001282#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001283 | (1 << SIGTTIN)
1284 | (1 << SIGTTOU)
1285 | (1 << SIGTSTP)
1286#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001287};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001288
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001289#if ENABLE_HUSH_FAST
1290static void SIGCHLD_handler(int sig UNUSED_PARAM)
1291{
1292 G.count_SIGCHLD++;
1293//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1294}
1295#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001296
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001297#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001298
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001299/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001300# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001301/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001302# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001303
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001304/* Restores tty foreground process group, and exits.
1305 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001306 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001307 * or called directly with -EXITCODE.
1308 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001309static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001310static void sigexit(int sig)
1311{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001312 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001313 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001314
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001315 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001316 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001317 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1318 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001319
1320 /* Not a signal, just exit */
1321 if (sig <= 0)
1322 _exit(- sig);
1323
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001324 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001325}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001326#else
1327
Denys Vlasenko8391c482010-05-22 17:50:43 +02001328# define disable_restore_tty_pgrp_on_exit() ((void)0)
1329# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001330
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001331#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001332
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001333/* Restores tty foreground process group, and exits. */
1334static void hush_exit(int exitcode) NORETURN;
1335static void hush_exit(int exitcode)
1336{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001337 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1338 /* Prevent recursion:
1339 * trap "echo Hi; exit" EXIT; exit
1340 */
1341 char *argv[] = { NULL, G.traps[0], NULL };
1342 G.traps[0] = NULL;
1343 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001344 builtin_eval(argv);
1345 free(argv[1]);
1346 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001347
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001348#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001349 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001350 sigexit(- (exitcode & 0xff));
1351#else
1352 exit(exitcode);
1353#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001354}
1355
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001356static int check_and_run_traps(int sig)
1357{
Dan Fandrichfdd7b562010-06-18 22:37:42 -07001358 static const struct timespec zero_timespec;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001359 smalluint save_rcode;
1360 int last_sig = 0;
1361
1362 if (sig)
1363 goto jump_in;
1364 while (1) {
1365 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1366 if (sig <= 0)
1367 break;
1368 jump_in:
1369 last_sig = sig;
1370 if (G.traps && G.traps[sig]) {
1371 if (G.traps[sig][0]) {
1372 /* We have user-defined handler */
1373 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1374 save_rcode = G.last_exitcode;
1375 builtin_eval(argv);
1376 free(argv[1]);
1377 G.last_exitcode = save_rcode;
1378 } /* else: "" trap, ignoring signal */
1379 continue;
1380 }
1381 /* not a trap: special action */
1382 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001383#if ENABLE_HUSH_FAST
1384 case SIGCHLD:
1385 G.count_SIGCHLD++;
1386//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1387 break;
1388#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001389 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001390 /* Builtin was ^C'ed, make it look prettier: */
1391 bb_putchar('\n');
1392 G.flag_SIGINT = 1;
1393 break;
1394#if ENABLE_HUSH_JOB
1395 case SIGHUP: {
1396 struct pipe *job;
1397 /* bash is observed to signal whole process groups,
1398 * not individual processes */
1399 for (job = G.job_list; job; job = job->next) {
1400 if (job->pgrp <= 0)
1401 continue;
1402 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1403 if (kill(- job->pgrp, SIGHUP) == 0)
1404 kill(- job->pgrp, SIGCONT);
1405 }
1406 sigexit(SIGHUP);
1407 }
1408#endif
1409 default: /* ignored: */
1410 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1411 break;
1412 }
1413 }
1414 return last_sig;
1415}
1416
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001417
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001418static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001419{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001420 if (force || G.cwd == NULL) {
1421 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1422 * we must not try to free(bb_msg_unknown) */
1423 if (G.cwd == bb_msg_unknown)
1424 G.cwd = NULL;
1425 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1426 if (!G.cwd)
1427 G.cwd = bb_msg_unknown;
1428 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001429 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001430}
1431
Denis Vlasenko83506862007-11-23 13:11:42 +00001432
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001433/*
1434 * Shell and environment variable support
1435 */
1436static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001437{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001438 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001439 struct variable *cur;
1440 int len;
1441
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001442 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001443 pp = &G.top_var;
1444 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001445 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001446 return pp;
1447 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001448 }
1449 return NULL;
1450}
1451
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001452static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001453{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001454 struct variable **pp = get_ptr_to_local_var(name);
1455 if (pp)
1456 return *pp;
1457 return NULL;
1458}
1459
Denys Vlasenko03dad222010-01-12 23:29:57 +01001460static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001461{
1462 struct variable **pp = get_ptr_to_local_var(name);
1463 if (pp)
1464 return strchr((*pp)->varstr, '=') + 1;
Denys Vlasenkodea47882009-10-09 15:40:49 +02001465 if (strcmp(name, "PPID") == 0)
1466 return utoa(G.root_ppid);
1467 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001468#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001469 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001470 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001471 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001472#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001473 return NULL;
1474}
1475
1476/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001477 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001478 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001479 * 0: do not change export flag
1480 * (if creating new variable, flag will be 0)
1481 * 1: set export flag and putenv the variable
1482 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001483 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001484 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001485#if !BB_MMU && ENABLE_HUSH_LOCAL
1486/* all params are used */
1487#elif BB_MMU && ENABLE_HUSH_LOCAL
1488#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1489 set_local_var(str, flg_export, local_lvl)
1490#elif BB_MMU && !ENABLE_HUSH_LOCAL
1491#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001492 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001493#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1494#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1495 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001496#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001497static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001498{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001499 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001500 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001501 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001502 int name_len;
1503
Denis Vlasenko950bd722009-04-21 11:23:56 +00001504 eq_sign = strchr(str, '=');
1505 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001506 free(str);
1507 return -1;
1508 }
1509
Denis Vlasenko950bd722009-04-21 11:23:56 +00001510 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001511 var_pp = &G.top_var;
1512 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001513 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001514 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001515 continue;
1516 }
1517 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001518 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001519#if !BB_MMU
1520 if (!flg_read_only)
1521#endif
1522 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001523 free(str);
1524 return -1;
1525 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001526 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001527 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1528 *eq_sign = '\0';
1529 unsetenv(str);
1530 *eq_sign = '=';
1531 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001532#if ENABLE_HUSH_LOCAL
1533 if (cur->func_nest_level < local_lvl) {
1534 /* New variable is declared as local,
1535 * and existing one is global, or local
1536 * from enclosing function.
1537 * Remove and save old one: */
1538 *var_pp = cur->next;
1539 cur->next = *G.shadowed_vars_pp;
1540 *G.shadowed_vars_pp = cur;
1541 /* bash 3.2.33(1) and exported vars:
1542 * # export z=z
1543 * # f() { local z=a; env | grep ^z; }
1544 * # f
1545 * z=a
1546 * # env | grep ^z
1547 * z=z
1548 */
1549 if (cur->flg_export)
1550 flg_export = 1;
1551 break;
1552 }
1553#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001554 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001555 free_and_exp:
1556 free(str);
1557 goto exp;
1558 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001559 if (cur->max_len != 0) {
1560 if (cur->max_len >= strlen(str)) {
1561 /* This one is from startup env, reuse space */
1562 strcpy(cur->varstr, str);
1563 goto free_and_exp;
1564 }
1565 } else {
1566 /* max_len == 0 signifies "malloced" var, which we can
1567 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001568 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001569 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001570 cur->max_len = 0;
1571 goto set_str_and_exp;
1572 }
1573
Denys Vlasenko295fef82009-06-03 12:47:26 +02001574 /* Not found - create new variable struct */
1575 cur = xzalloc(sizeof(*cur));
1576#if ENABLE_HUSH_LOCAL
1577 cur->func_nest_level = local_lvl;
1578#endif
1579 cur->next = *var_pp;
1580 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001581
1582 set_str_and_exp:
1583 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001584#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001585 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001586#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001587 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001588 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001589 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001590 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1591 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001592 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001593 if (flg_export == -1) {
1594 cur->flg_export = 0;
1595 /* unsetenv was already done */
1596 } else {
1597 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1598 return putenv(cur->varstr);
1599 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001600 }
1601 return 0;
1602}
1603
Denys Vlasenko6db47842009-09-05 20:15:17 +02001604/* Used at startup and after each cd */
1605static void set_pwd_var(int exp)
1606{
1607 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1608 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1609}
1610
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001611static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001612{
1613 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001614 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001615
1616 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001617 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001618 var_pp = &G.top_var;
1619 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001620 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1621 if (cur->flg_read_only) {
1622 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001623 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001624 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001625 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001626 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1627 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001628 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1629 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001630 if (!cur->max_len)
1631 free(cur->varstr);
1632 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001633 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001634 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001635 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001636 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001637 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001638}
1639
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001640static int unset_local_var(const char *name)
1641{
1642 return unset_local_var_len(name, strlen(name));
1643}
1644
1645static void unset_vars(char **strings)
1646{
1647 char **v;
1648
1649 if (!strings)
1650 return;
1651 v = strings;
1652 while (*v) {
1653 const char *eq = strchrnul(*v, '=');
1654 unset_local_var_len(*v, (int)(eq - *v));
1655 v++;
1656 }
1657 free(strings);
1658}
1659
Mike Frysinger98c52642009-04-02 10:02:37 +00001660#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko8391c482010-05-22 17:50:43 +02001661# define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1662# define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denys Vlasenko03dad222010-01-12 23:29:57 +01001663static char* FAST_FUNC endofname(const char *name)
Mike Frysinger98c52642009-04-02 10:02:37 +00001664{
1665 char *p;
1666
1667 p = (char *) name;
1668 if (!is_name(*p))
1669 return p;
1670 while (*++p) {
1671 if (!is_in_name(*p))
1672 break;
1673 }
1674 return p;
1675}
Denys Vlasenko6b01b712010-01-24 22:52:21 +01001676#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001677
Denys Vlasenko03dad222010-01-12 23:29:57 +01001678static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001679{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001680 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001681 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001682}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001683
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001684
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001685/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001686 * Helpers for "var1=val1 var2=val2 cmd" feature
1687 */
1688static void add_vars(struct variable *var)
1689{
1690 struct variable *next;
1691
1692 while (var) {
1693 next = var->next;
1694 var->next = G.top_var;
1695 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001696 if (var->flg_export) {
1697 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001698 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001699 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001700 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001701 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001702 var = next;
1703 }
1704}
1705
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001706static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001707{
1708 char **s;
1709 struct variable *old = NULL;
1710
1711 if (!strings)
1712 return old;
1713 s = strings;
1714 while (*s) {
1715 struct variable *var_p;
1716 struct variable **var_pp;
1717 char *eq;
1718
1719 eq = strchr(*s, '=');
1720 if (eq) {
1721 *eq = '\0';
1722 var_pp = get_ptr_to_local_var(*s);
1723 *eq = '=';
1724 if (var_pp) {
1725 /* Remove variable from global linked list */
1726 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001727 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001728 *var_pp = var_p->next;
1729 /* Add it to returned list */
1730 var_p->next = old;
1731 old = var_p;
1732 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001733 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001734 }
1735 s++;
1736 }
1737 return old;
1738}
1739
1740
1741/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001742 * in_str support
1743 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001744static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001745{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001746 int ch = *i->p;
1747 if (ch != '\0') {
1748 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001749 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001750 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001751 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001752}
1753
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001754static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001755{
1756 return *i->p;
1757}
1758
1759#if ENABLE_HUSH_INTERACTIVE
1760
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001761static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001762{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001763 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001764 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001765 if (G.PS1 == NULL)
1766 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001767 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001768 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001769 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001770 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001771 if (G.PS2 == NULL)
1772 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001773}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001774
1775static const char* setup_prompt_string(int promptmode)
1776{
1777 const char *prompt_str;
1778 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001779 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1780 /* Set up the prompt */
1781 if (promptmode == 0) { /* PS1 */
1782 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001783 /* bash uses $PWD value, even if it is set by user.
1784 * It uses current dir only if PWD is unset.
1785 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001786 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001787 prompt_str = G.PS1;
1788 } else
1789 prompt_str = G.PS2;
1790 } else
1791 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001792 debug_printf("result '%s'\n", prompt_str);
1793 return prompt_str;
1794}
1795
1796static void get_user_input(struct in_str *i)
1797{
1798 int r;
1799 const char *prompt_str;
1800
1801 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001802# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001803 /* Enable command line editing only while a command line
1804 * is actually being read */
1805 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001806 G.flag_SIGINT = 0;
1807 /* buglet: SIGINT will not make new prompt to appear _at once_,
1808 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001809 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 +00001810 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001811 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001812 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001813 i->eof_flag = (r < 0);
1814 if (i->eof_flag) { /* EOF/error detected */
1815 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1816 G.user_input_buf[1] = '\0';
1817 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001818# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001819 do {
1820 G.flag_SIGINT = 0;
1821 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001822 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001823 G.user_input_buf[0] = r = fgetc(i->file);
1824 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001825//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001826 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001827 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001828# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001829 i->p = G.user_input_buf;
1830}
1831
1832#endif /* INTERACTIVE */
1833
1834/* This is the magic location that prints prompts
1835 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001836static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001837{
1838 int ch;
1839
1840 /* If there is data waiting, eat it up */
1841 if (i->p && *i->p) {
1842#if ENABLE_HUSH_INTERACTIVE
1843 take_cached:
1844#endif
1845 ch = *i->p++;
1846 if (i->eof_flag && !*i->p)
1847 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001848 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001849 } else {
1850 /* need to double check i->file because we might be doing something
1851 * more complicated by now, like sourcing or substituting. */
1852#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001853 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001854 do {
1855 get_user_input(i);
1856 } while (!*i->p); /* need non-empty line */
1857 i->promptmode = 1; /* PS2 */
1858 i->promptme = 0;
1859 goto take_cached;
1860 }
1861#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001862 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001863 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001864 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001865#if ENABLE_HUSH_INTERACTIVE
1866 if (ch == '\n')
1867 i->promptme = 1;
1868#endif
1869 return ch;
1870}
1871
Denis Vlasenko913a2012009-04-05 22:17:04 +00001872/* All callers guarantee this routine will never
1873 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001874 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001875static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001876{
1877 int ch;
1878 if (i->p && *i->p) {
1879 if (i->eof_flag && !i->p[1])
1880 return EOF;
1881 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001882 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001883 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001884 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001885 i->eof_flag = (ch == EOF);
1886 i->peek_buf[0] = ch;
1887 i->peek_buf[1] = '\0';
1888 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001889 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001890 return ch;
1891}
1892
1893static void setup_file_in_str(struct in_str *i, FILE *f)
1894{
1895 i->peek = file_peek;
1896 i->get = file_get;
1897#if ENABLE_HUSH_INTERACTIVE
1898 i->promptme = 1;
1899 i->promptmode = 0; /* PS1 */
1900#endif
1901 i->file = f;
1902 i->p = NULL;
1903}
1904
1905static void setup_string_in_str(struct in_str *i, const char *s)
1906{
1907 i->peek = static_peek;
1908 i->get = static_get;
1909#if ENABLE_HUSH_INTERACTIVE
1910 i->promptme = 1;
1911 i->promptmode = 0; /* PS1 */
1912#endif
1913 i->p = s;
1914 i->eof_flag = 0;
1915}
1916
1917
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001918/*
1919 * o_string support
1920 */
1921#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001922
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001923static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001924{
1925 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001926 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001927 if (o->data)
1928 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001929}
1930
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001931static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001932{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001933 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001934 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001935}
1936
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001937static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1938{
1939 free(o->data);
1940}
1941
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001942static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001943{
1944 if (o->length + len > o->maxlen) {
1945 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1946 o->data = xrealloc(o->data, 1 + o->maxlen);
1947 }
1948}
1949
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001950static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001951{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001952 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1953 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001954 o->data[o->length] = ch;
1955 o->length++;
1956 o->data[o->length] = '\0';
1957}
1958
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001959static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001960{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001961 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001962 memcpy(&o->data[o->length], str, len);
1963 o->length += len;
1964 o->data[o->length] = '\0';
1965}
1966
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001967static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001968{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001969 o_addblock(o, str, strlen(str));
1970}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02001971
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001972#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001973static void nommu_addchr(o_string *o, int ch)
1974{
1975 if (o)
1976 o_addchr(o, ch);
1977}
1978#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001979# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001980#endif
1981
1982static void o_addstr_with_NUL(o_string *o, const char *str)
1983{
1984 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001985}
1986
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001987static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001988{
1989 while (len) {
1990 o_addchr(o, *str);
1991 if (*str++ == '\\'
1992 && (*str != '*' && *str != '?' && *str != '[')
1993 ) {
1994 o_addchr(o, '\\');
1995 }
1996 len--;
1997 }
1998}
1999
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002000#undef HUSH_BRACE_EXP
2001/*
2002 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2003 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2004 * Apparently, on unquoted $v bash still does globbing
2005 * ("v='*.txt'; echo $v" prints all .txt files),
2006 * but NOT brace expansion! Thus, there should be TWO independent
2007 * quoting mechanisms on $v expansion side: one protects
2008 * $v from brace expansion, and other additionally protects "$v" against globbing.
2009 * We have only second one.
2010 */
2011
2012#ifdef HUSH_BRACE_EXP
2013# define MAYBE_BRACES "{}"
2014#else
2015# define MAYBE_BRACES ""
2016#endif
2017
Eric Andersen25f27032001-04-26 23:22:31 +00002018/* My analysis of quoting semantics tells me that state information
2019 * is associated with a destination, not a source.
2020 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002021static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002022{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002023 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002024 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002025 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002026 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002027 o_grow_by(o, sz);
2028 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002029 o->data[o->length] = '\\';
2030 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002031 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002032 o->data[o->length] = ch;
2033 o->length++;
2034 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002035}
2036
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002037static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002038{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002039 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002040 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002041 sz++;
2042 o->data[o->length] = '\\';
2043 o->length++;
2044 }
2045 o_grow_by(o, sz);
2046 o->data[o->length] = ch;
2047 o->length++;
2048 o->data[o->length] = '\0';
2049}
2050
2051static void o_addQstr(o_string *o, const char *str, int len)
2052{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002053 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002054 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002055 return;
2056 }
2057 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002058 char ch;
2059 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002060 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002061 if (ordinary_cnt > len) /* paranoia */
2062 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002063 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002064 if (ordinary_cnt == len)
2065 return;
2066 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002067 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002068
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002069 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002070 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002071 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002072 sz++;
2073 o->data[o->length] = '\\';
2074 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002075 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002076 o_grow_by(o, sz);
2077 o->data[o->length] = ch;
2078 o->length++;
2079 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002080 }
2081}
2082
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002083/* A special kind of o_string for $VAR and `cmd` expansion.
2084 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002085 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002086 * list[i] contains an INDEX (int!) into this string data.
2087 * It means that if list[] needs to grow, data needs to be moved higher up
2088 * but list[i]'s need not be modified.
2089 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002090 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002091 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2092 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002093#if DEBUG_EXPAND || DEBUG_GLOB
2094static void debug_print_list(const char *prefix, o_string *o, int n)
2095{
2096 char **list = (char**)o->data;
2097 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2098 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002099
2100 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002101 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
2102 prefix, list, n, string_start, o->length, o->maxlen);
2103 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002104 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002105 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2106 o->data + (int)list[i] + string_start,
2107 o->data + (int)list[i] + string_start);
2108 i++;
2109 }
2110 if (n) {
2111 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002112 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002113 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002114 }
2115}
2116#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002117# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002118#endif
2119
2120/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2121 * in list[n] so that it points past last stored byte so far.
2122 * It returns n+1. */
2123static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002124{
2125 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002126 int string_start;
2127 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002128
2129 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002130 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2131 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002132 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002133 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002134 /* list[n] points to string_start, make space for 16 more pointers */
2135 o->maxlen += 0x10 * sizeof(list[0]);
2136 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002137 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002138 memmove(list + n + 0x10, list + n, string_len);
2139 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002140 } else {
2141 debug_printf_list("list[%d]=%d string_start=%d\n",
2142 n, string_len, string_start);
2143 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002144 } else {
2145 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002146 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2147 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002148 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2149 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002150 o->has_empty_slot = 0;
2151 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002152 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002153 return n + 1;
2154}
2155
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002156/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002157static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002158{
2159 char **list = (char**)o->data;
2160 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2161
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002162 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002163}
2164
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002165#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002166/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2167 * first, it processes even {a} (no commas), second,
2168 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002169 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002170 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002171
2172/* Helper */
2173static int glob_needed(const char *s)
2174{
2175 while (*s) {
2176 if (*s == '\\') {
2177 if (!s[1])
2178 return 0;
2179 s += 2;
2180 continue;
2181 }
2182 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2183 return 1;
2184 s++;
2185 }
2186 return 0;
2187}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002188/* Return pointer to next closing brace or to comma */
2189static const char *next_brace_sub(const char *cp)
2190{
2191 unsigned depth = 0;
2192 cp++;
2193 while (*cp != '\0') {
2194 if (*cp == '\\') {
2195 if (*++cp == '\0')
2196 break;
2197 cp++;
2198 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002199 }
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002200 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2201 break;
2202 if (*cp++ == '{') /*}*/
2203 depth++;
2204 }
2205
2206 return *cp != '\0' ? cp : NULL;
2207}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002208/* Recursive brace globber. Note: may garble pattern[]. */
2209static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002210{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002211 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002212 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002213 const char *next;
2214 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002215 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002216 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002217
2218 debug_printf_glob("glob_brace('%s')\n", pattern);
2219
2220 begin = pattern;
2221 while (1) {
2222 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002223 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002224 if (*begin == '{') /*}*/ {
2225 /* Find the first sub-pattern and at the same time
2226 * find the rest after the closing brace */
2227 next = next_brace_sub(begin);
2228 if (next == NULL) {
2229 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002230 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002231 }
2232 /*{*/ if (*next == '}') {
2233 /* "{abc}" with no commas - illegal
2234 * brace expr, disregard and skip it */
2235 begin = next + 1;
2236 continue;
2237 }
2238 break;
2239 }
2240 if (*begin == '\\' && begin[1] != '\0')
2241 begin++;
2242 begin++;
2243 }
2244 debug_printf_glob("begin:%s\n", begin);
2245 debug_printf_glob("next:%s\n", next);
2246
2247 /* Now find the end of the whole brace expression */
2248 rest = next;
2249 /*{*/ while (*rest != '}') {
2250 rest = next_brace_sub(rest);
2251 if (rest == NULL) {
2252 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002253 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002254 }
2255 debug_printf_glob("rest:%s\n", rest);
2256 }
2257 rest_len = strlen(++rest) + 1;
2258
2259 /* We are sure the brace expression is well-formed */
2260
2261 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002262 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002263
2264 /* We have a brace expression. BEGIN points to the opening {,
2265 * NEXT points past the terminator of the first element, and REST
2266 * points past the final }. We will accumulate result names from
2267 * recursive runs for each brace alternative in the buffer using
2268 * GLOB_APPEND. */
2269
2270 p = begin + 1;
2271 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002272 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002273 memcpy(
2274 mempcpy(
2275 mempcpy(new_pattern_buf,
2276 /* We know the prefix for all sub-patterns */
2277 pattern, begin - pattern),
2278 p, next - p),
2279 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002280
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002281 /* Note: glob_brace() may garble new_pattern_buf[].
2282 * That's why we re-copy prefix every time (1st memcpy above).
2283 */
2284 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002285 /*{*/ if (*next == '}') {
2286 /* We saw the last entry */
2287 break;
2288 }
2289 p = next + 1;
2290 next = next_brace_sub(next);
2291 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002292 free(new_pattern_buf);
2293 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002294
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002295 simple_glob:
2296 {
2297 int gr;
2298 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002299
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002300 memset(&globdata, 0, sizeof(globdata));
2301 gr = glob(pattern, 0, NULL, &globdata);
2302 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2303 if (gr != 0) {
2304 if (gr == GLOB_NOMATCH) {
2305 globfree(&globdata);
2306 /* NB: garbles parameter */
2307 unbackslash(pattern);
2308 o_addstr_with_NUL(o, pattern);
2309 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2310 return o_save_ptr_helper(o, n);
2311 }
2312 if (gr == GLOB_NOSPACE)
2313 bb_error_msg_and_die(bb_msg_memory_exhausted);
2314 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2315 * but we didn't specify it. Paranoia again. */
2316 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2317 }
2318 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2319 char **argv = globdata.gl_pathv;
2320 while (1) {
2321 o_addstr_with_NUL(o, *argv);
2322 n = o_save_ptr_helper(o, n);
2323 argv++;
2324 if (!*argv)
2325 break;
2326 }
2327 }
2328 globfree(&globdata);
2329 }
2330 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002331}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002332/* Performs globbing on last list[],
2333 * saving each result as a new list[].
2334 */
2335static int o_glob(o_string *o, int n)
2336{
2337 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002338
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002339 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2340 if (!o->data)
2341 return o_save_ptr_helper(o, n);
2342 pattern = o->data + o_get_last_ptr(o, n);
2343 debug_printf_glob("glob pattern '%s'\n", pattern);
2344 if (!glob_needed(pattern)) {
2345 /* unbackslash last string in o in place, fix length */
2346 o->length = unbackslash(pattern) - o->data;
2347 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2348 return o_save_ptr_helper(o, n);
2349 }
2350
2351 copy = xstrdup(pattern);
2352 /* "forget" pattern in o */
2353 o->length = pattern - o->data;
2354 n = glob_brace(copy, o, n);
2355 free(copy);
2356 if (DEBUG_GLOB)
2357 debug_print_list("o_glob returning", o, n);
2358 return n;
2359}
2360
Denys Vlasenko8391c482010-05-22 17:50:43 +02002361#else /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002362
2363/* Helper */
2364static int glob_needed(const char *s)
2365{
2366 while (*s) {
2367 if (*s == '\\') {
2368 if (!s[1])
2369 return 0;
2370 s += 2;
2371 continue;
2372 }
2373 if (*s == '*' || *s == '[' || *s == '?')
2374 return 1;
2375 s++;
2376 }
2377 return 0;
2378}
2379/* Performs globbing on last list[],
2380 * saving each result as a new list[].
2381 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002382static int o_glob(o_string *o, int n)
2383{
2384 glob_t globdata;
2385 int gr;
2386 char *pattern;
2387
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002388 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002389 if (!o->data)
2390 return o_save_ptr_helper(o, n);
2391 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002392 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002393 if (!glob_needed(pattern)) {
2394 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002395 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002396 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002397 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002398 return o_save_ptr_helper(o, n);
2399 }
2400
2401 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002402 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2403 * If we glob "*.\*" and don't find anything, we need
2404 * to fall back to using literal "*.*", but GLOB_NOCHECK
2405 * will return "*.\*"!
2406 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002407 gr = glob(pattern, 0, NULL, &globdata);
2408 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002409 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002410 if (gr == GLOB_NOMATCH) {
2411 globfree(&globdata);
2412 goto literal;
2413 }
2414 if (gr == GLOB_NOSPACE)
2415 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002416 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2417 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002418 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002419 }
2420 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2421 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002422 /* "forget" pattern in o */
2423 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002424 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002425 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002426 n = o_save_ptr_helper(o, n);
2427 argv++;
2428 if (!*argv)
2429 break;
2430 }
2431 }
2432 globfree(&globdata);
2433 if (DEBUG_GLOB)
2434 debug_print_list("o_glob returning", o, n);
2435 return n;
2436}
2437
Denys Vlasenko8391c482010-05-22 17:50:43 +02002438#endif /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002439
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002440/* If o->o_glob == 1, glob the string so far remembered.
2441 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002442static int o_save_ptr(o_string *o, int n)
2443{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002444 if (o->o_glob) { /* if globbing is requested */
2445 /* If o->has_empty_slot, list[n] was already globbed
2446 * (if it was requested back then when it was filled)
2447 * so don't do that again! */
2448 if (!o->has_empty_slot)
2449 return o_glob(o, n); /* o_save_ptr_helper is inside */
2450 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002451 return o_save_ptr_helper(o, n);
2452}
2453
2454/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002455static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002456{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002457 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002458 int string_start;
2459
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002460 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2461 if (DEBUG_EXPAND)
2462 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002463 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002464 list = (char**)o->data;
2465 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2466 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002467 while (n) {
2468 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002469 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002470 }
2471 return list;
2472}
2473
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002474
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002475/* Expansion can recurse */
2476#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002477static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002478#endif
2479static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002480#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002481#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002482 parse_stream_dquoted(dest, input, dquote_end)
2483#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002484static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002485 o_string *dest,
2486 struct in_str *input,
2487 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002488
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002489/* expand_strvec_to_strvec() takes a list of strings, expands
2490 * all variable references within and returns a pointer to
2491 * a list of expanded strings, possibly with larger number
2492 * of strings. (Think VAR="a b"; echo $VAR).
2493 * This new list is allocated as a single malloc block.
2494 * NULL-terminated list of char* pointers is at the beginning of it,
2495 * followed by strings themself.
2496 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002497
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002498/* Store given string, finalizing the word and starting new one whenever
2499 * we encounter IFS char(s). This is used for expanding variable values.
2500 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2501static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002502{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002503 while (1) {
2504 int word_len = strcspn(str, G.ifs);
2505 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002506 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002507 o_addQstr(output, str, word_len);
2508 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002509 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002510 str += word_len;
2511 }
2512 if (!*str) /* EOL - do not finalize word */
2513 break;
2514 o_addchr(output, '\0');
2515 debug_print_list("expand_on_ifs", output, n);
2516 n = o_save_ptr(output, n);
2517 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002518 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002519 debug_print_list("expand_on_ifs[1]", output, n);
2520 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002521}
2522
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002523/* Helper to expand $((...)) and heredoc body. These act as if
2524 * they are in double quotes, with the exception that they are not :).
2525 * Just the rules are similar: "expand only $var and `cmd`"
2526 *
2527 * Returns malloced string.
2528 * As an optimization, we return NULL if expansion is not needed.
2529 */
2530static char *expand_pseudo_dquoted(const char *str)
2531{
2532 char *exp_str;
2533 struct in_str input;
2534 o_string dest = NULL_O_STRING;
2535
2536 if (strchr(str, '$') == NULL
2537#if ENABLE_HUSH_TICK
2538 && strchr(str, '`') == NULL
2539#endif
2540 ) {
2541 return NULL;
2542 }
2543
2544 /* We need to expand. Example:
2545 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2546 */
2547 setup_string_in_str(&input, str);
2548 parse_stream_dquoted(NULL, &dest, &input, EOF);
2549 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2550 exp_str = expand_string_to_string(dest.data);
2551 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2552 o_free_unsafe(&dest);
2553 return exp_str;
2554}
2555
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002556#if ENABLE_SH_MATH_SUPPORT
2557static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2558{
2559 arith_eval_hooks_t hooks;
2560 arith_t res;
2561 char *exp_str;
2562
2563 hooks.lookupvar = get_local_var_value;
2564 hooks.setvar = set_local_var_from_halves;
2565 hooks.endofname = endofname;
2566 exp_str = expand_pseudo_dquoted(arg);
2567 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2568 free(exp_str);
2569 return res;
2570}
2571#endif
2572
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002573/* Expand all variable references in given string, adding words to list[]
2574 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2575 * to be filled). This routine is extremely tricky: has to deal with
2576 * variables/parameters with whitespace, $* and $@, and constructs like
2577 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02002578static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002579{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002580 /* or_mask is either 0 (normal case) or 0x80 -
2581 * expansion of right-hand side of assignment == 1-element expand.
2582 * It will also do no globbing, and thus we must not backslash-quote!
2583 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002584 char ored_ch;
2585 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002586
2587 ored_ch = 0;
2588
Denys Vlasenkof37eb392009-10-18 11:46:35 +02002589 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002590 debug_print_list("expand_vars_to_list", output, n);
2591 n = o_save_ptr(output, n);
2592 debug_print_list("expand_vars_to_list[0]", output, n);
2593
2594 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002595 char first_ch;
2596 int i;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002597 char *to_be_freed = NULL;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002598 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002599#if ENABLE_HUSH_TICK
2600 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002601#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002602#if ENABLE_SH_MATH_SUPPORT
2603 char arith_buf[sizeof(arith_t)*3 + 2];
2604#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002605 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002606 debug_print_list("expand_vars_to_list[1]", output, n);
2607 arg = ++p;
2608 p = strchr(p, SPECIAL_VAR_SYMBOL);
2609
2610 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2611 /* "$@" is special. Even if quoted, it can still
2612 * expand to nothing (not even an empty string) */
2613 if ((first_ch & 0x7f) != '@')
2614 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002615
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002616 switch (first_ch & 0x7f) {
2617 /* Highest bit in first_ch indicates that var is double-quoted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002618 case '*':
2619 case '@':
2620 i = 1;
2621 if (!G.global_argv[i])
2622 break;
2623 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2624 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002625 smallint sv = output->o_escape;
2626 /* unquoted var's contents should be globbed, so don't escape */
2627 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002628 while (G.global_argv[i]) {
2629 n = expand_on_ifs(output, n, G.global_argv[i]);
2630 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2631 if (G.global_argv[i++][0] && G.global_argv[i]) {
2632 /* this argv[] is not empty and not last:
2633 * put terminating NUL, start new word */
2634 o_addchr(output, '\0');
2635 debug_print_list("expand_vars_to_list[2]", output, n);
2636 n = o_save_ptr(output, n);
2637 debug_print_list("expand_vars_to_list[3]", output, n);
2638 }
2639 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002640 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002641 } else
2642 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2643 * and in this case should treat it like '$*' - see 'else...' below */
2644 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2645 while (1) {
2646 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2647 if (++i >= G.global_argc)
2648 break;
2649 o_addchr(output, '\0');
2650 debug_print_list("expand_vars_to_list[4]", output, n);
2651 n = o_save_ptr(output, n);
2652 }
2653 } else { /* quoted $*: add as one word */
2654 while (1) {
2655 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2656 if (!G.global_argv[++i])
2657 break;
2658 if (G.ifs[0])
2659 o_addchr(output, G.ifs[0]);
2660 }
2661 }
2662 break;
2663 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2664 /* "Empty variable", used to make "" etc to not disappear */
2665 arg++;
2666 ored_ch = 0x80;
2667 break;
2668#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002669 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002670 *p = '\0';
2671 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002672 /* Can't just stuff it into output o_string,
2673 * expanded result may need to be globbed
2674 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002675 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko647553a2009-11-15 19:58:19 +01002676 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenkocddbb612010-05-20 14:27:09 +02002677 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002678 val = subst_result.data;
2679 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002680#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002681#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002682 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002683 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002684 int errcode;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002685
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002686 arg++; /* skip '+' */
2687 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002688 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002689 res = expand_and_evaluate_arith(arg, &errcode);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002690
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002691 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002692 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002693 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002694 case -3:
2695 msg = "exponent less than 0";
2696 break;
2697 case -2:
2698 msg = "divide by 0";
2699 break;
2700 case -5:
2701 msg = "expression recursion loop detected";
2702 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002703 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002704 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002705 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002706 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002707 sprintf(arith_buf, arith_t_fmt, res);
2708 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002709 break;
2710 }
2711#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002712 default: { /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2713 char *var;
2714 char first_char;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002715 char exp_op;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002716 char exp_save = exp_save; /* for compiler */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002717 char *exp_saveptr; /* points to expansion operator */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002718 char *exp_word = exp_word; /* for compiler */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002719
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002720 var = arg;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002721 *p = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002722 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2723 first_char = arg[0] = first_ch & 0x7f;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002724 exp_op = 0;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002725
2726 if (first_char == '#' && arg[1] && !exp_saveptr) {
Mike Frysinger6379bb42009-03-28 18:55:03 +00002727 /* handle length expansion ${#var} */
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002728 var++;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002729 exp_op = 'L';
Mike Frysinger6379bb42009-03-28 18:55:03 +00002730 } else {
2731 /* maybe handle parameter expansion */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002732 if (exp_saveptr /* if 2nd char is one of expansion operators */
2733 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2734 ) {
2735 /* ${?:0}, ${#[:]%0} etc */
2736 exp_saveptr = var + 1;
2737 } else {
2738 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2739 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2740 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002741 exp_op = exp_save = *exp_saveptr;
2742 if (exp_op) {
2743 exp_word = exp_saveptr + 1;
2744 if (exp_op == ':') {
2745 exp_op = *exp_word++;
2746 if (ENABLE_HUSH_BASH_COMPAT
2747 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2748 ) {
2749 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2750 exp_op = ':';
2751 exp_word--;
2752 }
2753 }
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002754 *exp_saveptr = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002755 } /* else: it's not an expansion op, but bare ${var} */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002756 }
2757
2758 /* lookup the variable in question */
2759 if (isdigit(var[0])) {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002760 /* parse_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002761 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002762 if (i < G.global_argc)
2763 val = G.global_argv[i];
2764 /* else val remains NULL: $N with too big N */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002765 } else {
2766 switch (var[0]) {
2767 case '$': /* pid */
2768 val = utoa(G.root_pid);
2769 break;
2770 case '!': /* bg pid */
2771 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2772 break;
2773 case '?': /* exitcode */
2774 val = utoa(G.last_exitcode);
2775 break;
2776 case '#': /* argc */
2777 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2778 break;
2779 default:
2780 val = get_local_var_value(var);
2781 }
2782 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002783
2784 /* handle any expansions */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002785 if (exp_op == 'L') {
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002786 debug_printf_expand("expand: length(%s)=", val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002787 val = utoa(val ? strlen(val) : 0);
2788 debug_printf_expand("%s\n", val);
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002789 } else if (exp_op) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002790 if (exp_op == '%' || exp_op == '#') {
Denys Vlasenko53b51332010-05-20 21:46:45 +02002791 /* Standard-mandated substring removal ops:
2792 * ${parameter%word} - remove smallest suffix pattern
2793 * ${parameter%%word} - remove largest suffix pattern
2794 * ${parameter#word} - remove smallest prefix pattern
2795 * ${parameter##word} - remove largest prefix pattern
2796 *
2797 * Word is expanded to produce a glob pattern.
2798 * Then var's value is matched to it and matching part removed.
2799 */
Mike Frysinger57e74672009-04-09 23:00:33 +00002800 if (val) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002801 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002802 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002803 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002804 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002805 exp_word++;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002806 val = to_be_freed = xstrdup(val);
Denys Vlasenko74369502010-05-21 19:52:01 +02002807 {
2808 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2809 if (exp_exp_word)
2810 exp_word = exp_exp_word;
2811 loc = scan(to_be_freed, exp_word, match_at_left);
2812 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2813 // exp_op, to_be_freed, exp_word, loc);
2814 free(exp_exp_word);
2815 }
2816 if (loc) { /* match was found */
2817 if (match_at_left) /* # or ## */
2818 val = loc;
2819 else /* % or %% */
2820 *loc = '\0';
2821 }
Mike Frysinger57e74672009-04-09 23:00:33 +00002822 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002823 } else if (exp_op == ':') {
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02002824#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002825 /* It's ${var:N[:M]} bashism.
2826 * Note that in encoded form it has TWO parts:
2827 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002828 */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002829 arith_t beg, len;
2830 int errcode = 0;
2831
2832 beg = expand_and_evaluate_arith(exp_word, &errcode);
2833 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2834 *p++ = SPECIAL_VAR_SYMBOL;
2835 exp_word = p;
2836 p = strchr(p, SPECIAL_VAR_SYMBOL);
2837 *p = '\0';
2838 len = expand_and_evaluate_arith(exp_word, &errcode);
2839 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2840
2841 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2842 if (beg < 0) /* bash compat */
2843 beg = 0;
2844 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002845 if (len == 0 || !val || beg >= strlen(val))
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002846 val = "";
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002847 else {
2848 /* Paranoia. What if user entered 9999999999999
2849 * which fits in arith_t but not int? */
2850 if (len >= INT_MAX)
2851 len = INT_MAX;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002852 val = to_be_freed = xstrndup(val + beg, len);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002853 }
2854 debug_printf_varexp("val:'%s'\n", val);
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002855 } else
2856#endif
2857 {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002858 die_if_script("malformed ${%s:...}", var);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002859 val = "";
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002860 }
2861 } else { /* one of "-=+?" */
Denys Vlasenko53b51332010-05-20 21:46:45 +02002862 /* Standard-mandated substitution ops:
2863 * ${var?word} - indicate error if unset
2864 * If var is unset, word (or a message indicating it is unset
2865 * if word is null) is written to standard error
2866 * and the shell exits with a non-zero exit status.
2867 * Otherwise, the value of var is substituted.
2868 * ${var-word} - use default value
2869 * If var is unset, word is substituted.
2870 * ${var=word} - assign and use default value
2871 * If var is unset, word is assigned to var.
2872 * In all cases, final value of var is substituted.
2873 * ${var+word} - use alternative value
2874 * If var is unset, null is substituted.
2875 * Otherwise, word is substituted.
2876 *
2877 * Word is subjected to tilde expansion, parameter expansion,
2878 * command substitution, and arithmetic expansion.
2879 * If word is not needed, it is not expanded.
2880 *
2881 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2882 * but also treat null var as if it is unset.
2883 */
2884 int use_word = (!val || ((exp_save == ':') && !val[0]));
Mike Frysingera4f331d2009-04-07 06:03:22 +00002885 if (exp_op == '+')
Denys Vlasenko53b51332010-05-20 21:46:45 +02002886 use_word = !use_word;
Mike Frysingera4f331d2009-04-07 06:03:22 +00002887 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
Denys Vlasenko53b51332010-05-20 21:46:45 +02002888 (exp_save == ':') ? "true" : "false", use_word);
2889 if (use_word) {
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002890 to_be_freed = expand_pseudo_dquoted(exp_word);
2891 if (to_be_freed)
2892 exp_word = to_be_freed;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002893 if (exp_op == '?') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002894 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002895 die_if_script("%s: %s",
2896 var,
2897 exp_word[0] ? exp_word : "parameter null or not set"
2898 );
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002899//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002900 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002901 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002902 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002903
Mike Frysingera4f331d2009-04-07 06:03:22 +00002904 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002905 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002906 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002907 /* mimic bash message */
2908 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002909 val = NULL;
2910 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002911 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002912 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002913 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002914 }
2915 }
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002916 } /* one of "-=+?" */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002917
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002918 *exp_saveptr = exp_save;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002919 } /* if (exp_op) */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002920
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002921 arg[0] = first_ch;
2922#if ENABLE_HUSH_TICK
2923 store_val:
2924#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002925 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002926 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002927 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002928 /* unquoted var's contents should be globbed, so don't escape */
2929 smallint sv = output->o_escape;
2930 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002931 n = expand_on_ifs(output, n, val);
2932 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002933 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002934 }
2935 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002936 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002937 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002938 } /* default: */
2939 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002940
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002941 if (val) {
2942 o_addQstr(output, val, strlen(val));
2943 }
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002944 free(to_be_freed);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002945 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002946 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002947 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002948
2949#if ENABLE_HUSH_TICK
2950 o_free(&subst_result);
2951#endif
2952 arg = ++p;
2953 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2954
2955 if (arg[0]) {
2956 debug_print_list("expand_vars_to_list[a]", output, n);
2957 /* this part is literal, and it was already pre-quoted
2958 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002959 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002960 debug_print_list("expand_vars_to_list[b]", output, n);
2961 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2962 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2963 ) {
2964 n--;
2965 /* allow to reuse list[n] later without re-growth */
2966 output->has_empty_slot = 1;
2967 } else {
2968 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002969 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002970 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002971}
2972
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002973static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002974{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002975 int n;
2976 char **list;
2977 char **v;
2978 o_string output = NULL_O_STRING;
2979
2980 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002981 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002982 /* (unquoted $var will temporarily switch it off) */
2983 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002984 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002985
2986 n = 0;
2987 v = argv;
2988 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002989 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002990 v++;
2991 }
2992 debug_print_list("expand_variables", &output, n);
2993
2994 /* output.data (malloced in one block) gets returned in "list" */
2995 list = o_finalize_list(&output, n);
2996 debug_print_strings("expand_variables[1]", list);
2997 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002998}
2999
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003000static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003001{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003002 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00003003}
3004
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003005#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003006static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3007{
3008 return expand_variables(argv, 0x80);
3009}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003010#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003011
3012#ifdef CMD_SINGLEWORD_NOGLOB_COND
3013static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3014{
3015 int n;
3016 char **list;
3017 char **v;
3018 o_string output = NULL_O_STRING;
3019
3020 n = 0;
3021 v = argv;
3022 while (*v) {
3023 int is_var = is_well_formed_var_name(*v, '=');
3024 /* is_var * 0x80: singleword expansion for vars */
3025 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3026
3027 /* Subtle! expand_vars_to_list did not glob last word yet.
3028 * It does this only when fed with further data.
3029 * Therefore we set globbing flags AFTER it, not before:
3030 */
3031
3032 /* if it is not recognizably abc=...; then: */
3033 output.o_escape = !is_var; /* protect against globbing for "$var" */
3034 /* (unquoted $var will temporarily switch it off) */
3035 output.o_glob = !is_var; /* and indeed do globbing */
3036 v++;
3037 }
3038 debug_print_list("expand_cond", &output, n);
3039
3040 /* output.data (malloced in one block) gets returned in "list" */
3041 list = o_finalize_list(&output, n);
3042 debug_print_strings("expand_cond[1]", list);
3043 return list;
3044}
3045#endif
3046
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003047/* Used for expansion of right hand of assignments */
3048/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
3049 * "v=/bin/c*" */
3050static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00003051{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003052 char *argv[2], **list;
3053
3054 argv[0] = (char*)str;
3055 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003056 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003057 if (HUSH_DEBUG)
3058 if (!list[0] || list[1])
3059 bb_error_msg_and_die("BUG in varexp2");
3060 /* actually, just move string 2*sizeof(char*) bytes back */
3061 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003062 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003063 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3064 return (char*)list;
3065}
3066
3067/* Used for "eval" builtin */
3068static char* expand_strvec_to_string(char **argv)
3069{
3070 char **list;
3071
3072 list = expand_variables(argv, 0x80);
3073 /* Convert all NULs to spaces */
3074 if (list[0]) {
3075 int n = 1;
3076 while (list[n]) {
3077 if (HUSH_DEBUG)
3078 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3079 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003080 /* bash uses ' ' regardless of $IFS contents */
3081 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003082 n++;
3083 }
3084 }
3085 overlapping_strcpy((char*)list, list[0]);
3086 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3087 return (char*)list;
3088}
3089
3090static char **expand_assignments(char **argv, int count)
3091{
3092 int i;
3093 char **p = NULL;
3094 /* Expand assignments into one string each */
3095 for (i = 0; i < count; i++) {
3096 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
3097 }
3098 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00003099}
3100
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003101
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003102#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003103/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003104void re_execute_shell(char ***to_free, const char *s,
3105 char *g_argv0, char **g_argv,
3106 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003107
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003108static void reset_traps_to_defaults(void)
3109{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003110 /* This function is always called in a child shell
3111 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003112 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003113 unsigned sig;
3114 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003115
Denys Vlasenko67f71862009-09-25 14:21:06 +02003116 /* Child shells are not interactive.
3117 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3118 * Testcase: (while :; do :; done) + ^Z should background.
3119 * Same goes for SIGTERM, SIGHUP, SIGINT.
3120 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003121 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02003122 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003123
Denys Vlasenko67f71862009-09-25 14:21:06 +02003124 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3125 * Stupid. It can be done with *single* &= op, but we can't use
3126 * the fact that G.blocked_set is implemented as a bitmask
3127 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003128 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3129 sig = 1;
3130 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02003131 if (mask & 1) {
3132 /* Careful. Only if no trap or trap is not "" */
3133 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3134 sigdelset(&G.blocked_set, sig);
3135 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003136 mask >>= 1;
3137 if (!mask)
3138 break;
3139 sig++;
3140 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02003141 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003142 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003143
3144 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003145 mask = G.non_DFL_mask;
3146 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02003147 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003148 continue;
3149 free(G.traps[sig]);
3150 G.traps[sig] = NULL;
3151 /* There is no signal for 0 (EXIT) */
3152 if (sig == 0)
3153 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003154 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003155 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02003156 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003157 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003158 continue;
3159 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003160 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003161 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003162}
3163
3164#else /* !BB_MMU */
3165
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003166static void re_execute_shell(char ***to_free, const char *s,
3167 char *g_argv0, char **g_argv,
3168 char **builtin_argv) NORETURN;
3169static void re_execute_shell(char ***to_free, const char *s,
3170 char *g_argv0, char **g_argv,
3171 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003172{
Denys Vlasenko8391c482010-05-22 17:50:43 +02003173# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003174 /* delims + 2 * (number of bytes in printed hex numbers) */
3175 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003176 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003177 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003178# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003179 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003180# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003181 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003182 unsigned cnt;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003183 unsigned long long empty_trap_mask;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003184
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003185 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003186 argv = heredoc_argv;
3187 argv[0] = (char *) G.argv0_for_re_execing;
3188 argv[1] = (char *) "-<";
3189 argv[2] = (char *) s;
3190 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00003191 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003192 goto do_exec;
3193 }
3194
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003195 cnt = 0;
3196 pp = builtin_argv;
3197 if (pp) while (*pp++)
3198 cnt++;
3199
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003200 empty_trap_mask = 0;
3201 if (G.traps) {
3202 int sig;
3203 for (sig = 1; sig < NSIG; sig++) {
3204 if (G.traps[sig] && !G.traps[sig][0])
3205 empty_trap_mask |= 1LL << sig;
3206 }
3207 }
3208
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003209 sprintf(param_buf, NOMMU_HACK_FMT
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003210 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02003211 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003212 , (unsigned) G.last_bg_pid
3213 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003214 , cnt
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003215 , empty_trap_mask
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003216 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003217 );
Denys Vlasenko8391c482010-05-22 17:50:43 +02003218# undef NOMMU_HACK_FMT
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003219 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003220 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003221 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003222 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003223 for (cur = G.top_var; cur; cur = cur->next) {
3224 if (!cur->flg_export || cur->flg_read_only)
3225 cnt += 2;
3226 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003227# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003228 for (funcp = G.top_func; funcp; funcp = funcp->next)
3229 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003230# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003231 pp = g_argv;
3232 while (*pp++)
3233 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003234 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003235 *pp++ = (char *) G.argv0_for_re_execing;
3236 *pp++ = param_buf;
3237 for (cur = G.top_var; cur; cur = cur->next) {
3238 if (cur->varstr == hush_version_str)
3239 continue;
3240 if (cur->flg_read_only) {
3241 *pp++ = (char *) "-R";
3242 *pp++ = cur->varstr;
3243 } else if (!cur->flg_export) {
3244 *pp++ = (char *) "-V";
3245 *pp++ = cur->varstr;
3246 }
3247 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003248# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003249 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3250 *pp++ = (char *) "-F";
3251 *pp++ = funcp->name;
3252 *pp++ = funcp->body_as_string;
3253 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003254# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003255 /* We can pass activated traps here. Say, -Tnn:trap_string
3256 *
3257 * However, POSIX says that subshells reset signals with traps
3258 * to SIG_DFL.
3259 * I tested bash-3.2 and it not only does that with true subshells
3260 * of the form ( list ), but with any forked children shells.
3261 * I set trap "echo W" WINCH; and then tried:
3262 *
3263 * { echo 1; sleep 20; echo 2; } &
3264 * while true; do echo 1; sleep 20; echo 2; break; done &
3265 * true | { echo 1; sleep 20; echo 2; } | cat
3266 *
3267 * In all these cases sending SIGWINCH to the child shell
3268 * did not run the trap. If I add trap "echo V" WINCH;
3269 * _inside_ group (just before echo 1), it works.
3270 *
3271 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003272 * Even if we would use signal handlers instead of signal masking
3273 * in order to implement trap handling,
3274 * exec syscall below resets signals to SIG_DFL for us.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003275 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003276 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003277 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003278 if (builtin_argv) {
3279 while (*++builtin_argv)
3280 *pp++ = *builtin_argv;
3281 *pp++ = (char *) "";
3282 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003283 *pp++ = g_argv0;
3284 while (*g_argv)
3285 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003286 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003287 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003288
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003289 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003290 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3291 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003292 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003293 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003294 if (argv[0][0] == '/')
3295 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003296 xfunc_error_retval = 127;
3297 bb_error_msg_and_die("can't re-execute the shell");
3298}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003299#endif /* !BB_MMU */
3300
3301
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003302static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003303{
3304 struct fd_pair pair;
3305 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003306 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003307 /* the _body_ of heredoc (misleading field name) */
3308 const char *heredoc = redir->rd_filename;
3309 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003310#if !BB_MMU
3311 char **to_free;
3312#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003313
3314 expanded = NULL;
3315 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3316 expanded = expand_pseudo_dquoted(heredoc);
3317 if (expanded)
3318 heredoc = expanded;
3319 }
3320 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003321
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003322 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003323 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003324 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003325
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003326 /* Try writing without forking. Newer kernels have
3327 * dynamically growing pipes. Must use non-blocking write! */
3328 ndelay_on(pair.wr);
3329 while (1) {
3330 written = write(pair.wr, heredoc, len);
3331 if (written <= 0)
3332 break;
3333 len -= written;
3334 if (len == 0) {
3335 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00003336 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003337 return;
3338 }
3339 heredoc += written;
3340 }
3341 ndelay_off(pair.wr);
3342
3343 /* Okay, pipe buffer was not big enough */
3344 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003345 * for the unsuspecting parent process. Child creates a grandchild
3346 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003347 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003348#if !BB_MMU
3349 to_free = NULL;
3350#endif
Pascal Bellard926031b2010-07-04 15:32:38 +02003351 pid = xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003352 if (pid == 0) {
3353 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003354 disable_restore_tty_pgrp_on_exit();
Pascal Bellard926031b2010-07-04 15:32:38 +02003355 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003356 if (pid != 0)
3357 _exit(0);
3358 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003359 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003360#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003361 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003362 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003363#else
3364 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003365 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003366 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003367#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003368 }
3369 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003370#if ENABLE_HUSH_FAST
3371 G.count_SIGCHLD++;
3372//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3373#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003374 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003375#if !BB_MMU
3376 free(to_free);
3377#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003378 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003379 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003380 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003381}
3382
Eric Andersen25f27032001-04-26 23:22:31 +00003383/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3384 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003385static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003386{
3387 int openfd, mode;
3388 struct redir_struct *redir;
3389
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003390 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003391 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003392 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003393 if (squirrel && redir->rd_fd < 3
3394 && squirrel[redir->rd_fd] < 0
3395 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003396 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003397 }
3398 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3399 * of the heredoc */
3400 debug_printf_parse("set heredoc '%s'\n",
3401 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003402 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003403 continue;
3404 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003405
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003406 if (redir->rd_dup == REDIRFD_TO_FILE) {
3407 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003408 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003409 if (redir->rd_filename == NULL) {
3410 /* Something went wrong in the parse.
3411 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003412 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003413 continue;
3414 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003415 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003416 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003417 openfd = open_or_warn(p, mode);
3418 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003419 if (openfd < 0) {
3420 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003421 * bash and ash both lose it as well (though zsh doesn't!) */
3422//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003423 return 1;
3424 }
3425 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003426 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003427 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003428 }
3429
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003430 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003431 if (squirrel && redir->rd_fd < 3
3432 && squirrel[redir->rd_fd] < 0
3433 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003434 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003435 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003436 if (openfd == REDIRFD_CLOSE) {
3437 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003438 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003439 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003440 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003441 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003442 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003443 }
Eric Andersen25f27032001-04-26 23:22:31 +00003444 }
3445 }
3446 return 0;
3447}
3448
3449static void restore_redirects(int squirrel[])
3450{
3451 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003452 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003453 fd = squirrel[i];
3454 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003455 /* We simply die on error */
3456 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003457 }
3458 }
3459}
3460
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003461
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003462static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003463
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003464/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003465static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003466{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003467 char **p;
3468 struct command *command;
3469 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003470 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003471
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003472 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003473 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003474 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003475 for (i = 0; i < pi->num_cmds; i++) {
3476 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003477 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003478 if (command->argv) {
3479 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003480 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003481 }
3482 free_strings(command->argv);
3483 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003484 }
3485 /* not "else if": on syntax error, we may have both! */
3486 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003487 debug_printf_clean(" begin group (cmd_type:%d)\n",
3488 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003489 free_pipe_list(command->group);
3490 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003491 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003492 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003493 /* else is crucial here.
3494 * If group != NULL, child_func is meaningless */
3495#if ENABLE_HUSH_FUNCTIONS
3496 else if (command->child_func) {
3497 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3498 command->child_func->parent_cmd = NULL;
3499 }
3500#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003501#if !BB_MMU
3502 free(command->group_as_string);
3503 command->group_as_string = NULL;
3504#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003505 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003506 debug_printf_clean(" redirect %d%s",
3507 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003508 /* guard against the case >$FOO, where foo is unset or blank */
3509 if (r->rd_filename) {
3510 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3511 free(r->rd_filename);
3512 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003513 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003514 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003515 rnext = r->next;
3516 free(r);
3517 }
3518 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003519 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003520 free(pi->cmds); /* children are an array, they get freed all at once */
3521 pi->cmds = NULL;
3522#if ENABLE_HUSH_JOB
3523 free(pi->cmdtext);
3524 pi->cmdtext = NULL;
3525#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003526}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003527
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003528static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003529{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003530 struct pipe *pi, *next;
3531
3532 for (pi = head; pi; pi = next) {
3533#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003534 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003535#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003536 free_pipe(pi);
3537 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003538 next = pi->next;
3539 /*pi->next = NULL;*/
3540 free(pi);
3541 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003542}
3543
3544
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003545static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003546#if BB_MMU
3547#define parse_stream(pstring, input, end_trigger) \
3548 parse_stream(input, end_trigger)
3549#endif
3550static struct pipe *parse_stream(char **pstring,
3551 struct in_str *input,
3552 int end_trigger);
3553static void parse_and_run_string(const char *s);
3554
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003555
Mike Frysinger93cadc22009-05-27 17:06:25 -04003556static char *find_in_path(const char *arg)
3557{
3558 char *ret = NULL;
3559 const char *PATH = get_local_var_value("PATH");
3560
3561 if (!PATH)
3562 return NULL;
3563
3564 while (1) {
3565 const char *end = strchrnul(PATH, ':');
3566 int sz = end - PATH; /* must be int! */
3567
3568 free(ret);
3569 if (sz != 0) {
3570 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3571 } else {
3572 /* We have xxx::yyyy in $PATH,
3573 * it means "use current dir" */
3574 ret = xstrdup(arg);
3575 }
3576 if (access(ret, F_OK) == 0)
3577 break;
3578
3579 if (*end == '\0') {
3580 free(ret);
3581 return NULL;
3582 }
3583 PATH = end + 1;
3584 }
3585
3586 return ret;
3587}
3588
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003589static const struct built_in_command* find_builtin_helper(const char *name,
3590 const struct built_in_command *x,
3591 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003592{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003593 while (x != end) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01003594 if (strcmp(name, x->b_cmd) != 0) {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003595 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003596 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003597 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003598 debug_printf_exec("found builtin '%s'\n", name);
3599 return x;
3600 }
3601 return NULL;
3602}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003603static const struct built_in_command* find_builtin1(const char *name)
3604{
3605 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3606}
3607static const struct built_in_command* find_builtin(const char *name)
3608{
3609 const struct built_in_command *x = find_builtin1(name);
3610 if (x)
3611 return x;
3612 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3613}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003614
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003615#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003616static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003617{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003618 struct function **funcpp = &G.top_func;
3619 while (*funcpp) {
3620 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003621 break;
3622 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003623 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003624 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003625 return funcpp;
3626}
3627
3628static const struct function *find_function(const char *name)
3629{
3630 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003631 if (funcp)
3632 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003633 return funcp;
3634}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003635
Denis Vlasenkobc569742009-04-12 20:35:19 +00003636/* Note: takes ownership on name ptr */
3637static struct function *new_function(char *name)
3638{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003639 struct function **funcpp = find_function_slot(name);
3640 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003641
Denys Vlasenko873273d2009-09-12 14:47:41 +02003642 if (funcp != NULL) {
3643 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003644 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3645 if (!cmd) {
3646 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3647 free(funcp->name);
3648 /* Note: if !funcp->body, do not free body_as_string!
3649 * This is a special case of "-F name body" function:
3650 * body_as_string was not malloced! */
3651 if (funcp->body) {
3652 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003653# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003654 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003655# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003656 }
3657 } else {
3658 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3659 cmd->argv[0] = funcp->name;
3660 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003661# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003662 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003663# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003664 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003665 } else {
3666 debug_printf_exec("remembering new function '%s'\n", name);
3667 funcp = *funcpp = xzalloc(sizeof(*funcp));
3668 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003669 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003670
Denis Vlasenkobc569742009-04-12 20:35:19 +00003671 funcp->name = name;
3672 return funcp;
3673}
3674
Denis Vlasenko40e84372009-04-18 11:23:38 +00003675static void unset_func(const char *name)
3676{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003677 struct function **funcpp = find_function_slot(name);
3678 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003679
Denys Vlasenko873273d2009-09-12 14:47:41 +02003680 if (funcp != NULL) {
3681 debug_printf_exec("freeing function '%s'\n", funcp->name);
3682 *funcpp = funcp->next;
3683 /* funcp is unlinked now, deleting it.
3684 * Note: if !funcp->body, the function was created by
3685 * "-F name body", do not free ->body_as_string
3686 * and ->name as they were not malloced. */
3687 if (funcp->body) {
3688 free_pipe_list(funcp->body);
3689 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003690# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003691 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003692# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003693 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003694 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003695 }
3696}
3697
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003698# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003699#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003700 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003701# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003702static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003703 const struct function *funcp,
3704 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003705static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003706 const struct function *funcp,
3707 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003708{
3709# if BB_MMU
3710 int n = 1;
3711
3712 argv[0] = G.global_argv[0];
3713 G.global_argv = argv;
3714 while (*++argv)
3715 n++;
3716 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003717 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003718 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003719 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003720 _exit(n);
3721# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003722 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003723 funcp->body_as_string,
3724 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003725 argv + 1,
3726 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003727# endif
3728}
3729
3730static int run_function(const struct function *funcp, char **argv)
3731{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003732 int rc;
3733 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003734 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003735
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003736 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003737
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003738 /* "we are in function, ok to use return" */
3739 sv_flg = G.flag_return_in_progress;
3740 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003741# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003742 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003743# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003744
Denis Vlasenkobc569742009-04-12 20:35:19 +00003745 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003746# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003747 if (!funcp->body) {
3748 /* Function defined by -F */
3749 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003750 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003751 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003752# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003753 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003754 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003755 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003756
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003757# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003758 {
3759 struct variable *var;
3760 struct variable **var_pp;
3761
3762 var_pp = &G.top_var;
3763 while ((var = *var_pp) != NULL) {
3764 if (var->func_nest_level < G.func_nest_level) {
3765 var_pp = &var->next;
3766 continue;
3767 }
3768 /* Unexport */
3769 if (var->flg_export)
3770 bb_unsetenv(var->varstr);
3771 /* Remove from global list */
3772 *var_pp = var->next;
3773 /* Free */
3774 if (!var->max_len)
3775 free(var->varstr);
3776 free(var);
3777 }
3778 G.func_nest_level--;
3779 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003780# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003781 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003782
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003783 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003784
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003785 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003786}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003787#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003788
3789
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003790#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003791#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003792 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003793#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003794#define exec_builtin(to_free, x, argv) \
3795 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003796#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003797static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003798 const struct built_in_command *x,
3799 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003800static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003801 const struct built_in_command *x,
3802 char **argv)
3803{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003804#if BB_MMU
Denys Vlasenko17323a62010-01-28 01:57:05 +01003805 int rcode = x->b_function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003806 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003807 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003808#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003809 /* On NOMMU, we must never block!
3810 * Example: { sleep 99 | read line; } & echo Ok
3811 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003812 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003813 argv[0],
3814 G.global_argv[0],
3815 G.global_argv + 1,
3816 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003817#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003818}
3819
3820
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003821static void execvp_or_die(char **argv) NORETURN;
3822static void execvp_or_die(char **argv)
3823{
3824 debug_printf_exec("execing '%s'\n", argv[0]);
3825 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3826 execvp(argv[0], argv);
3827 bb_perror_msg("can't execute '%s'", argv[0]);
3828 _exit(127); /* bash compat */
3829}
3830
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003831#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003832static void dump_cmd_in_x_mode(char **argv)
3833{
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003834 if (G_x_mode && argv) {
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003835 /* We want to output the line in one write op */
3836 char *buf, *p;
3837 int len;
3838 int n;
3839
3840 len = 3;
3841 n = 0;
3842 while (argv[n])
3843 len += strlen(argv[n++]) + 1;
3844 buf = xmalloc(len);
3845 buf[0] = '+';
3846 p = buf + 1;
3847 n = 0;
3848 while (argv[n])
3849 p += sprintf(p, " %s", argv[n++]);
3850 *p++ = '\n';
3851 *p = '\0';
3852 fputs(buf, stderr);
3853 free(buf);
3854 }
3855}
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003856#else
3857# define dump_cmd_in_x_mode(argv) ((void)0)
3858#endif
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003859
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003860#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003861#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3862 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3863#define pseudo_exec(nommu_save, command, argv_expanded) \
3864 pseudo_exec(command, argv_expanded)
3865#endif
3866
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003867/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003868 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003869 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003870 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003871 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003872static void pseudo_exec_argv(nommu_save_t *nommu_save,
3873 char **argv, int assignment_cnt,
3874 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003875static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003876 char **argv, int assignment_cnt,
3877 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003878{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003879 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003880
Denis Vlasenko9504e442008-10-29 01:19:15 +00003881 new_env = expand_assignments(argv, assignment_cnt);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003882 dump_cmd_in_x_mode(new_env);
Denys Vlasenko889550b2010-07-14 19:01:25 +02003883
3884 if (!argv[assignment_cnt]) {
3885 /* Case when we are here: ... | var=val | ...
3886 * (note that we do not exit early, i.e., do not optimize out
3887 * expand_assignments(): think about ... | var=`sleep 1` | ...
3888 */
3889 free_strings(new_env);
3890 _exit(EXIT_SUCCESS);
3891 }
3892
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003893#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003894 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003895 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003896 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003897 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003898#else
3899 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003900 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003901#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02003902
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003903 if (argv_expanded) {
3904 argv = argv_expanded;
3905 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003906 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003907#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003908 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003909#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003910 }
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003911 dump_cmd_in_x_mode(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003912
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003913#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3914 if (strchr(argv[0], '/') != NULL)
3915 goto skip;
3916#endif
3917
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003918 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003919 * Depending on context, this might be redundant. But it's
3920 * easier to waste a few CPU cycles than it is to figure out
3921 * if this is one of those cases.
3922 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003923 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003924 /* On NOMMU, it is more expensive to re-execute shell
3925 * just in order to run echo or test builtin.
3926 * It's better to skip it here and run corresponding
3927 * non-builtin later. */
3928 const struct built_in_command *x;
3929 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003930 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003931 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003932 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003933 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003934#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003935 /* Check if the command matches any functions */
3936 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003937 const struct function *funcp = find_function(argv[0]);
3938 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003939 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003940 }
3941 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003942#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003943
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003944#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003945 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003946 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003947 int a = find_applet_by_name(argv[0]);
3948 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003949# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003950 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003951 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003952 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003953 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003954# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003955 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003956 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003957 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3958 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003959 /* If they called chroot or otherwise made the binary no longer
3960 * executable, fall through */
3961 }
3962 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003963#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003964
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003965#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003966 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003967#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003968 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003969}
3970
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003971/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003972 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003973static void pseudo_exec(nommu_save_t *nommu_save,
3974 struct command *command,
3975 char **argv_expanded) NORETURN;
3976static void pseudo_exec(nommu_save_t *nommu_save,
3977 struct command *command,
3978 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003979{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003980 if (command->argv) {
3981 pseudo_exec_argv(nommu_save, command->argv,
3982 command->assignment_cnt, argv_expanded);
3983 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003984
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003985 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003986 /* Cases when we are here:
3987 * ( list )
3988 * { list } &
3989 * ... | ( list ) | ...
3990 * ... | { list } | ...
3991 */
3992#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003993 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003994 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003995 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003996 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003997 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003998 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003999 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004000#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004001 re_execute_shell(&nommu_save->argv_from_re_execing,
4002 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004003 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02004004 G.global_argv + 1,
4005 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00004006#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004007 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004008
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004009 /* Case when we are here: ... | >file */
4010 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004011 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00004012}
4013
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004014#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004015static const char *get_cmdtext(struct pipe *pi)
4016{
4017 char **argv;
4018 char *p;
4019 int len;
4020
4021 /* This is subtle. ->cmdtext is created only on first backgrounding.
4022 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004023 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004024 if (pi->cmdtext)
4025 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004026 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004027 if (!argv || !argv[0]) {
4028 pi->cmdtext = xzalloc(1);
4029 return pi->cmdtext;
4030 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004031
4032 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004033 do {
4034 len += strlen(*argv) + 1;
4035 } while (*++argv);
4036 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004037 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004038 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004039 do {
4040 len = strlen(*argv);
4041 memcpy(p, *argv, len);
4042 p += len;
4043 *p++ = ' ';
4044 } while (*++argv);
4045 p[-1] = '\0';
4046 return pi->cmdtext;
4047}
4048
Eric Andersenbafd94f2001-05-02 16:11:59 +00004049static void insert_bg_job(struct pipe *pi)
4050{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004051 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004052 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004053
4054 /* Linear search for the ID of the job to use */
4055 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004056 for (job = G.job_list; job; job = job->next)
4057 if (job->jobid >= pi->jobid)
4058 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004059
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004060 /* Add job to the list of running jobs */
4061 jobp = &G.job_list;
4062 while ((job = *jobp) != NULL)
4063 jobp = &job->next;
4064 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00004065
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004066 *job = *pi; /* physical copy */
4067 job->next = NULL;
4068 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4069 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004070 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004071 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004072 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004073 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004074 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00004075
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004076 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004077 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
4078 /* Last command's pid goes to $! */
4079 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
4080 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004081}
4082
Eric Andersenbafd94f2001-05-02 16:11:59 +00004083static void remove_bg_job(struct pipe *pi)
4084{
4085 struct pipe *prev_pipe;
4086
Denis Vlasenko87a86552008-07-29 19:43:10 +00004087 if (pi == G.job_list) {
4088 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004089 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004090 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004091 while (prev_pipe->next != pi)
4092 prev_pipe = prev_pipe->next;
4093 prev_pipe->next = pi->next;
4094 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004095 if (G.job_list)
4096 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00004097 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00004098 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00004099}
Eric Andersen028b65b2001-06-28 01:10:11 +00004100
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004101/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00004102static void delete_finished_bg_job(struct pipe *pi)
4103{
4104 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004105 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004106 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004107 free(pi);
4108}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004109#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004110
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004111/* Check to see if any processes have exited -- if they
4112 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00004113static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00004114{
Eric Andersenc798b072001-06-22 06:23:03 +00004115 int attributes;
4116 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004117#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00004118 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004119#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00004120 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004121 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004122
Denis Vlasenkod5762932009-03-31 11:22:57 +00004123 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4124
Eric Andersenc798b072001-06-22 06:23:03 +00004125 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004126 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00004127 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00004128
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004129 errno = 0;
4130#if ENABLE_HUSH_FAST
4131 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4132//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4133//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02004134 /* There was neither fork nor SIGCHLD since last waitpid */
4135 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004136 if (!G.we_have_children) {
4137 errno = ECHILD;
4138 return -1;
4139 }
4140 if (fg_pipe == NULL) { /* is WNOHANG set? */
4141 /* We have children, but they did not exit
4142 * or stop yet (we saw no SIGCHLD) */
4143 return 0;
4144 }
4145 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4146 }
4147#endif
4148
Denis Vlasenko1359da62007-04-21 23:27:30 +00004149/* Do we do this right?
4150 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004151 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00004152 * [3]+ Stopped sleep 20 | false
4153 * bash-3.00# echo $?
4154 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004155 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00004156 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004157 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004158 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004159 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004160 int dead;
4161
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004162#if ENABLE_HUSH_FAST
4163 i = G.count_SIGCHLD;
4164#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004165 childpid = waitpid(-1, &status, attributes);
4166 if (childpid <= 0) {
4167 if (childpid && errno != ECHILD)
4168 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004169#if ENABLE_HUSH_FAST
4170 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004171 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004172 G.handled_SIGCHLD = i;
4173//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4174 }
4175#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004176 break;
4177 }
4178 dead = WIFEXITED(status) || WIFSIGNALED(status);
4179
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00004180#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00004181 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004182 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004183 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4184 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004185 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004186 childpid, WTERMSIG(status), WEXITSTATUS(status));
4187 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004188 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004189 childpid, WEXITSTATUS(status));
4190#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004191 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00004192 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004193 for (i = 0; i < fg_pipe->num_cmds; i++) {
4194 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4195 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004196 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004197 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004198 fg_pipe->cmds[i].pid = 0;
4199 fg_pipe->alive_cmds--;
4200 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004201 /* last process gives overall exitstatus */
4202 rcode = WEXITSTATUS(status);
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004203 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00004204 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004205 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00004206 */
4207 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00004208 int sig = WTERMSIG(status);
4209 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004210 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4211 * Maybe we need to use sig | 128? */
4212 rcode = sig + 128;
Denis Vlasenko40e84372009-04-18 11:23:38 +00004213 }
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004214 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00004215 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004216 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004217 fg_pipe->cmds[i].is_stopped = 1;
4218 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00004219 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004220 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4221 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4222 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004223 /* All processes in fg pipe have exited or stopped */
4224/* Note: *non-interactive* bash does not continue if all processes in fg pipe
4225 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4226 * and "killall -STOP cat" */
4227 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004228#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004229 if (fg_pipe->alive_cmds)
4230 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004231#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004232 return rcode;
4233 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02004234 if (!fg_pipe->alive_cmds)
4235 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004236 }
4237 /* There are still running processes in the fg pipe */
4238 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00004239 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004240 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00004241 }
4242
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004243#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004244 /* We asked to wait for bg or orphaned children */
4245 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004246 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004247 for (i = 0; i < pi->num_cmds; i++) {
4248 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004249 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00004250 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00004251 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004252 /* Happens when shell is used as init process (init=/bin/sh) */
4253 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004254 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00004255
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004256 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00004257 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00004258 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004259 pi->cmds[i].pid = 0;
4260 pi->alive_cmds--;
4261 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004262 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00004263 printf(JOB_STATUS_FORMAT, pi->jobid,
4264 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004265 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004266 }
4267 } else {
4268 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004269 pi->cmds[i].is_stopped = 1;
4270 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004271 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004272#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004273 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004274
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004275 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00004276}
4277
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004278#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00004279static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4280{
4281 pid_t p;
4282 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04004283 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004284 /* Job finished, move the shell to the foreground */
4285 p = getpgrp(); /* our process group id */
4286 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4287 tcsetpgrp(G_interactive_fd, p);
4288 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00004289 return rcode;
4290}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004291#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00004292
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004293/* Start all the jobs, but don't wait for anything to finish.
4294 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00004295 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00004296 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00004297 * to finish to determine the exit status of the pipe. If the pipe
4298 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00004299 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00004300 * return value.
4301 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00004302 * Returns -1 only if started some children. IOW: we have to
4303 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00004304 *
4305 * The only case when we do not need to [v]fork is when the pipe
4306 * is single, non-backgrounded, non-subshell command. Examples:
4307 * cmd ; ... { list } ; ...
4308 * cmd && ... { list } && ...
4309 * cmd || ... { list } || ...
4310 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4311 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004312 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00004313 *
4314 * Cases when we must fork:
4315 * non-single: cmd | cmd
4316 * backgrounded: cmd & { list } &
4317 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00004318 */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02004319static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004320{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004321 static const char *const null_ptr = NULL;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004322
4323 int cmd_no;
4324 int next_infd;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004325 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004326 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004327 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004328 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004329 /* it is not always needed, but we aim to smaller code */
4330 int squirrel[] = { -1, -1, -1 };
4331 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004332
Denis Vlasenko552433b2009-04-04 19:29:21 +00004333 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004334 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004335
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004336 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004337 pi->stopped_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004338 command = &pi->cmds[0];
Denis Vlasenko552433b2009-04-04 19:29:21 +00004339 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004340
Denis Vlasenko552433b2009-04-04 19:29:21 +00004341 if (pi->num_cmds != 1
4342 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004343 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00004344 ) {
4345 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004346 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004347
Denis Vlasenko552433b2009-04-04 19:29:21 +00004348 pi->alive_cmds = 1;
4349
4350 debug_printf_exec(": group:%p argv:'%s'\n",
4351 command->group, command->argv ? command->argv[0] : "NONE");
4352
4353 if (command->group) {
4354#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004355 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004356 /* "executing" func () { list } */
4357 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004358
Denis Vlasenkobc569742009-04-12 20:35:19 +00004359 funcp = new_function(command->argv[0]);
4360 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004361 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004362# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004363 funcp->body_as_string = command->group_as_string;
4364 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004365# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004366 command->group = NULL;
4367 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00004368 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4369 funcp->parent_cmd = command;
4370 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004371
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004372 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4373 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00004374 return EXIT_SUCCESS;
4375 }
4376#endif
4377 /* { list } */
4378 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004379 rcode = 1; /* exitcode if redir failed */
4380 if (setup_redirects(command, squirrel) == 0) {
4381 debug_printf_exec(": run_list\n");
4382 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004383 }
Eric Andersen04407e52001-06-07 16:42:05 +00004384 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004385 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004386 debug_leave();
4387 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004388 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004389 }
4390
Denis Vlasenko552433b2009-04-04 19:29:21 +00004391 argv = command->argv ? command->argv : (char **) &null_ptr;
4392 {
4393 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004394#if ENABLE_HUSH_FUNCTIONS
4395 const struct function *funcp;
4396#else
4397 enum { funcp = 0 };
4398#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004399 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004400 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004401
Denis Vlasenko552433b2009-04-04 19:29:21 +00004402 if (argv[command->assignment_cnt] == NULL) {
4403 /* Assignments, but no command */
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004404 /* Ensure redirects take effect (that is, create files).
4405 * Try "a=t >file": */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004406 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004407 restore_redirects(squirrel);
4408 /* Set shell variables */
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004409 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004410 bb_putchar_stderr('+');
Denis Vlasenko552433b2009-04-04 19:29:21 +00004411 while (*argv) {
4412 p = expand_string_to_string(*argv);
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004413 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004414 fprintf(stderr, " %s", p);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004415 debug_printf_exec("set shell var:'%s'->'%s'\n",
4416 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004417 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004418 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004419 }
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004420 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004421 bb_putchar_stderr('\n');
Denys Vlasenkob3389de2010-07-15 12:33:37 +02004422 /* Redirect error sets $? to 1. Otherwise,
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004423 * if evaluating assignment value set $?, retain it.
4424 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4425 if (rcode == 0)
4426 rcode = G.last_exitcode;
Denis Vlasenko552433b2009-04-04 19:29:21 +00004427 /* Do we need to flag set_local_var() errors?
4428 * "assignment to readonly var" and "putenv error"
4429 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004430 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004431 debug_leave();
4432 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004433 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00004434 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004435
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004436 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004437 if (0) {}
4438#if ENABLE_HUSH_BASH_COMPAT
4439 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004440 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4441 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004442#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004443#ifdef CMD_SINGLEWORD_NOGLOB_COND
4444 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4445 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4446
4447 }
4448#endif
4449 else {
4450 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4451 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004452
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004453 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004454 if (!argv_expanded[0]) {
Denys Vlasenko385cc592010-01-12 06:47:39 +01004455 free(argv_expanded);
Mike Frysinger28736c32009-10-18 01:11:45 -04004456 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004457 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004458 }
4459
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004460 x = find_builtin(argv_expanded[0]);
4461#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004462 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004463 if (!x)
4464 funcp = find_function(argv_expanded[0]);
4465#endif
4466 if (x || funcp) {
4467 if (!funcp) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01004468 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004469 debug_printf("exec with redirects only\n");
4470 rcode = setup_redirects(command, NULL);
4471 goto clean_up_and_ret1;
4472 }
Eric Andersen25f27032001-04-26 23:22:31 +00004473 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004474 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004475 * This is perfect for work that comes after exec().
4476 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004477 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004478 rcode = setup_redirects(command, squirrel);
4479 if (rcode == 0) {
4480 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004481 dump_cmd_in_x_mode(new_env);
4482 dump_cmd_in_x_mode(argv_expanded);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004483 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004484 if (!funcp) {
4485 debug_printf_exec(": builtin '%s' '%s'...\n",
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004486 x->b_cmd, argv_expanded[1]);
Denys Vlasenko17323a62010-01-28 01:57:05 +01004487 rcode = x->b_function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004488 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004489 }
4490#if ENABLE_HUSH_FUNCTIONS
4491 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004492# if ENABLE_HUSH_LOCAL
4493 struct variable **sv;
4494 sv = G.shadowed_vars_pp;
4495 G.shadowed_vars_pp = &old_vars;
4496# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004497 debug_printf_exec(": function '%s' '%s'...\n",
4498 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004499 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004500# if ENABLE_HUSH_LOCAL
4501 G.shadowed_vars_pp = sv;
4502# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004503 }
4504#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004505 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004506 clean_up_and_ret:
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004507 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004508 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004509 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004510 clean_up_and_ret1:
4511 free(argv_expanded);
4512 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004513 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004514 debug_printf_exec("run_pipe return %d\n", rcode);
4515 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004516 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004517
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004518 if (ENABLE_FEATURE_SH_STANDALONE) {
4519 int n = find_applet_by_name(argv_expanded[0]);
4520 if (n >= 0 && APPLET_IS_NOFORK(n)) {
4521 rcode = setup_redirects(command, squirrel);
4522 if (rcode == 0) {
4523 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004524 dump_cmd_in_x_mode(new_env);
4525 dump_cmd_in_x_mode(argv_expanded);
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004526 old_vars = set_vars_and_save_old(new_env);
4527 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4528 argv_expanded[0], argv_expanded[1]);
4529 rcode = run_nofork_applet(n, argv_expanded);
4530 }
4531 goto clean_up_and_ret;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004532 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004533 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00004534 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004535 }
4536
Denis Vlasenko552433b2009-04-04 19:29:21 +00004537 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004538 /* NB: argv_expanded may already be created, and that
4539 * might include `cmd` runs! Do not rerun it! We *must*
4540 * use argv_expanded if it's non-NULL */
4541
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004542 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004543 pi->alive_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004544 next_infd = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004545
Denys Vlasenko889550b2010-07-14 19:01:25 +02004546 cmd_no = 0;
4547 while (cmd_no < pi->num_cmds) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004548 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004549#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004550 volatile nommu_save_t nommu_save;
4551 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004552 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004553 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004554 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004555#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02004556 command = &pi->cmds[cmd_no];
4557 cmd_no++;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004558 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004559 debug_printf_exec(": pipe member '%s' '%s'...\n",
4560 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004561 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004562 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004563 }
Eric Andersen25f27032001-04-26 23:22:31 +00004564
4565 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004566 pipefds.rd = 0;
4567 pipefds.wr = 1;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004568 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004569 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004570
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004571 command->pid = BB_MMU ? fork() : vfork();
4572 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004573#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004574 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004575 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004576
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004577 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004578 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004579 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004580 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004581 pgrp = pi->pgrp;
4582 if (pgrp < 0) /* true for 1st process only */
4583 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004584 if (setpgid(0, pgrp) == 0
4585 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004586 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004587 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004588 /* We do it in *every* child, not just first,
4589 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004590 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004591 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004592 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004593#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004594 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4595 /* 1st cmd in backgrounded pipe
4596 * should have its stdin /dev/null'ed */
4597 close(0);
4598 if (open(bb_dev_null, O_RDONLY))
4599 xopen("/", O_RDONLY);
4600 } else {
Denys Vlasenko889550b2010-07-14 19:01:25 +02004601 xmove_fd(next_infd, 0);
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004602 }
4603 xmove_fd(pipefds.wr, 1);
4604 if (pipefds.rd > 1)
4605 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004606 /* Like bash, explicit redirects override pipes,
4607 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004608 if (setup_redirects(command, NULL))
4609 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004610
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004611 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004612 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4613
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004614 /* Stores to nommu_save list of env vars putenv'ed
4615 * (NOMMU, on MMU we don't need that) */
4616 /* cast away volatility... */
4617 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004618 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004619 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004620
Denis Vlasenkof9375282009-04-05 19:13:39 +00004621 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004622#if ENABLE_HUSH_FAST
4623 G.count_SIGCHLD++;
4624//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4625#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004626 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004627#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004628 /* Clean up after vforked child */
4629 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004630 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004631 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004632 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004633#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004634 free(argv_expanded);
4635 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004636 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004637 /* Clearly indicate, was it fork or vfork */
Pascal Bellard926031b2010-07-04 15:32:38 +02004638 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004639 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004640 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004641#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004642 /* Second and next children need to know pid of first one */
4643 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004644 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004645#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004646 }
Eric Andersen25f27032001-04-26 23:22:31 +00004647
Denys Vlasenko889550b2010-07-14 19:01:25 +02004648 if (cmd_no > 1)
4649 close(next_infd);
4650 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004651 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004652 /* Pass read (output) pipe end to next iteration */
Denys Vlasenko889550b2010-07-14 19:01:25 +02004653 next_infd = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004654 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004655
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004656 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004657 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004658 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4659 return 1;
4660 }
4661
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004662 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004663 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004664 return -1;
4665}
4666
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004667#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004668static void debug_print_tree(struct pipe *pi, int lvl)
4669{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004670 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004671 [PIPE_SEQ] = "SEQ",
4672 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004673 [PIPE_OR ] = "OR" ,
4674 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004675 };
4676 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004677 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004678# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004679 [RES_IF ] = "IF" ,
4680 [RES_THEN ] = "THEN" ,
4681 [RES_ELIF ] = "ELIF" ,
4682 [RES_ELSE ] = "ELSE" ,
4683 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004684# endif
4685# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004686 [RES_FOR ] = "FOR" ,
4687 [RES_WHILE] = "WHILE",
4688 [RES_UNTIL] = "UNTIL",
4689 [RES_DO ] = "DO" ,
4690 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004691# endif
4692# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004693 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004694# endif
4695# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004696 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004697 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004698 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004699 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004700 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004701# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004702 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004703 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004704 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004705 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004706 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004707 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004708 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004709# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004710 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004711# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004712 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004713
4714 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004715
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004716 pin = 0;
4717 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004718 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4719 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004720 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004721 while (prn < pi->num_cmds) {
4722 struct command *command = &pi->cmds[prn];
4723 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004724
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004725 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004726 lvl*2, "", prn,
4727 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004728 if (command->group) {
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004729 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004730 CMDTYPE[command->cmd_type],
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004731 argv
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004732# if !BB_MMU
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004733 , " group_as_string:", command->group_as_string
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004734# else
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004735 , "", ""
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004736# endif
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004737 );
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004738 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004739 prn++;
4740 continue;
4741 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004742 if (argv) while (*argv) {
4743 fprintf(stderr, " '%s'", *argv);
4744 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004745 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004746 fprintf(stderr, "\n");
4747 prn++;
4748 }
4749 pi = pi->next;
4750 pin++;
4751 }
4752}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004753#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004754
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004755/* NB: called by pseudo_exec, and therefore must not modify any
4756 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004757static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004758{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004759#if ENABLE_HUSH_CASE
4760 char *case_word = NULL;
4761#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004762#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004763 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004764 char **for_lcur = NULL;
4765 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004766#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004767 smallint last_followup;
4768 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004769#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004770 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004771#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004772 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004773#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004774#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004775 smallint rword; /* enum reserved_style */
4776 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004777#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004778
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004779 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004780 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004781
Denis Vlasenko06810332007-05-21 23:30:54 +00004782#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004783 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004784 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4785 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004786 continue;
4787 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004788 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004789 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004790 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004791 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004792 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004793 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004794 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004795 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004796 continue;
4797 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004798 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4799 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004800 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004801 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004802 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004803 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004804 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004805 }
4806 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004807#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004808
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004809 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004810 * in order to return, no direct "return" statements please.
4811 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004812
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004813#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004814 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004815#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004816
Denis Vlasenko0e151382009-04-06 18:40:31 +00004817#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004818 rword = RES_NONE;
4819 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004820#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004821 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004822 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004823
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004824 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004825 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004826 if (G.flag_SIGINT)
4827 break;
4828
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004829 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004830 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4831 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004832#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004833 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004834 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004835 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004836 /* start of a loop: remember where loop starts */
4837 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004838 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004839 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004840#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004841 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004842 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004843 if ((rcode == 0 && last_followup == PIPE_OR)
4844 || (rcode != 0 && last_followup == PIPE_AND)
4845 ) {
4846 /* It is "<true> || CMD" or "<false> && CMD"
4847 * and we should not execute CMD */
4848 debug_printf_exec("skipped cmd because of || or &&\n");
4849 last_followup = pi->followup;
4850 continue;
4851 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004852 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004853 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004854 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004855#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004856 if (cond_code) {
4857 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004858 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004859 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004860 /* "if <false> THEN cmd": skip cmd */
4861 continue;
4862 }
4863 } else {
4864 if (rword == RES_ELSE || rword == RES_ELIF) {
4865 /* "if <true> then ... ELSE/ELIF cmd":
4866 * skip cmd and all following ones */
4867 break;
4868 }
4869 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004870#endif
4871#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004872 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004873 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004874 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004875
4876 static const char encoded_dollar_at[] ALIGN1 = {
4877 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4878 }; /* encoded representation of "$@" */
4879 static const char *const encoded_dollar_at_argv[] = {
4880 encoded_dollar_at, NULL
4881 }; /* argv list with one element: "$@" */
4882 char **vals;
4883
4884 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004885 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004886 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004887 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004888 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004889 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004890 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004891 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004892 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004893 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004894 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004895 debug_print_strings("for_list made from", vals);
4896 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004897 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004898 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004899 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004900 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004901 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004902 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004903 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004904 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004905 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004906 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004907 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004908 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004909 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 +02004910 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004911 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004912 if (rword == RES_IN) {
4913 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4914 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004915 if (rword == RES_DONE) {
4916 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004917 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004918#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004919#if ENABLE_HUSH_CASE
4920 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004921 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004922 continue;
4923 }
4924 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004925 char **argv;
4926
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004927 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4928 break;
4929 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004930 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004931 while (*argv) {
4932 char *pattern = expand_string_to_string(*argv);
4933 /* TODO: which FNM_xxx flags to use? */
4934 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4935 free(pattern);
4936 if (cond_code == 0) { /* match! we will execute this branch */
4937 free(case_word); /* make future "word)" stop */
4938 case_word = NULL;
4939 break;
4940 }
4941 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004942 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004943 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004944 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004945 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004946 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004947 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004948 }
4949#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004950 /* Just pressing <enter> in shell should check for jobs.
4951 * OTOH, in non-interactive shell this is useless
4952 * and only leads to extra job checks */
4953 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004954 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004955 goto check_jobs_and_continue;
4956 continue;
4957 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004958
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004959 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004960 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004961 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004962 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004963 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004964 {
4965 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004966#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004967 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004968#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004969 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4970 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004971 /* We ran a builtin, function, or group.
4972 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004973 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004974 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004975 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004976 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004977#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004978 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004979 if (G.flag_break_continue) {
4980 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004981 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004982 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004983 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004984 G.depth_break_continue--;
4985 if (G.depth_break_continue == 0)
4986 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004987 /* else: e.g. "continue 2" should *break* once, *then* continue */
4988 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004989 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004990 goto check_jobs_and_break;
4991 /* "continue": simulate end of loop */
4992 rword = RES_DONE;
4993 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004994 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004995#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004996#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004997 if (G.flag_return_in_progress == 1) {
4998 /* same as "goto check_jobs_and_break" */
4999 checkjobs(NULL);
5000 break;
5001 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005002#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005003 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005004 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005005 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005006 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5007 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005008 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005009#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00005010 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005011 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00005012#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005013 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005014 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005015 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005016#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005017 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005018 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005019 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005020 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005021 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005022 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005023#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005024 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005025 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005026 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005027 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005028 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005029 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00005030 }
5031 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005032
5033 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00005034#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00005035 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005036 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00005037#endif
5038#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005039 /* Beware of "while false; true; do ..."! */
5040 if (pi->next && pi->next->res_word == RES_DO) {
5041 if (rword == RES_WHILE) {
5042 if (rcode) {
5043 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005044 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005045 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5046 goto check_jobs_and_break;
5047 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00005048 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005049 if (rword == RES_UNTIL) {
5050 if (!rcode) {
5051 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005052 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005053 checkjobs(NULL);
5054 break;
5055 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005056 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005057 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005058#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00005059
5060 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00005061 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005062 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00005063
5064#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00005065 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00005066#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00005067#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005068 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00005069 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00005070 free(for_list);
5071#endif
5072#if ENABLE_HUSH_CASE
5073 free(case_word);
5074#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005075 debug_leave();
5076 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00005077 return rcode;
5078}
5079
Eric Andersen25f27032001-04-26 23:22:31 +00005080/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00005081static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00005082{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005083 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00005084 debug_printf_exec("run_and_free_list entered\n");
Denys Vlasenko202a2d12010-07-16 12:36:14 +02005085 if (!G.n_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005086 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00005087 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005088 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005089 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00005090 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00005091 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005092 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00005093 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00005094 return rcode;
5095}
5096
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005097
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00005098static struct pipe *new_pipe(void)
5099{
Eric Andersen25f27032001-04-26 23:22:31 +00005100 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00005101 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005102 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005103 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00005104 return pi;
5105}
5106
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005107/* Command (member of a pipe) is complete, or we start a new pipe
5108 * if ctx->command is NULL.
5109 * No errors possible here.
5110 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005111static int done_command(struct parse_context *ctx)
5112{
5113 /* The command is really already in the pipe structure, so
5114 * advance the pipe counter and make a new, null command. */
5115 struct pipe *pi = ctx->pipe;
5116 struct command *command = ctx->command;
5117
5118 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005119 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005120 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005121 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005122 }
5123 pi->num_cmds++;
5124 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005125 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005126 } else {
5127 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5128 }
5129
5130 /* Only real trickiness here is that the uncommitted
5131 * command structure is not counted in pi->num_cmds. */
5132 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005133 ctx->command = command = &pi->cmds[pi->num_cmds];
5134 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005135 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005136 return pi->num_cmds; /* used only for 0/nonzero check */
5137}
5138
5139static void done_pipe(struct parse_context *ctx, pipe_style type)
5140{
5141 int not_null;
5142
5143 debug_printf_parse("done_pipe entered, followup %d\n", type);
5144 /* Close previous command */
5145 not_null = done_command(ctx);
5146 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005147#if HAS_KEYWORDS
5148 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5149 ctx->ctx_inverted = 0;
5150 ctx->pipe->res_word = ctx->ctx_res_w;
5151#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005152
5153 /* Without this check, even just <enter> on command line generates
5154 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005155 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005156 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00005157#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005158 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00005159#endif
5160#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005161 || ctx->ctx_res_w == RES_DONE
5162 || ctx->ctx_res_w == RES_FOR
5163 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00005164#endif
5165#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005166 || ctx->ctx_res_w == RES_ESAC
5167#endif
5168 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005169 struct pipe *new_p;
5170 debug_printf_parse("done_pipe: adding new pipe: "
5171 "not_null:%d ctx->ctx_res_w:%d\n",
5172 not_null, ctx->ctx_res_w);
5173 new_p = new_pipe();
5174 ctx->pipe->next = new_p;
5175 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005176 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005177 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005178 * This is used to control execution.
5179 * RES_FOR and RES_IN are NOT sticky (needed to support
5180 * cases where variable or value happens to match a keyword):
5181 */
5182#if ENABLE_HUSH_LOOPS
5183 if (ctx->ctx_res_w == RES_FOR
5184 || ctx->ctx_res_w == RES_IN)
5185 ctx->ctx_res_w = RES_NONE;
5186#endif
5187#if ENABLE_HUSH_CASE
5188 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005189 ctx->ctx_res_w = RES_CASE_BODY;
5190 if (ctx->ctx_res_w == RES_CASE)
5191 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005192#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005193 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005194 /* Create the memory for command, roughly:
5195 * ctx->pipe->cmds = new struct command;
5196 * ctx->command = &ctx->pipe->cmds[0];
5197 */
5198 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005199 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005200 }
5201 debug_printf_parse("done_pipe return\n");
5202}
5203
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005204static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005205{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005206 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00005207 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005208 /* Create the memory for command, roughly:
5209 * ctx->pipe->cmds = new struct command;
5210 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005211 */
5212 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005213}
5214
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005215/* If a reserved word is found and processed, parse context is modified
5216 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00005217 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005218#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005219struct reserved_combo {
5220 char literal[6];
5221 unsigned char res;
5222 unsigned char assignment_flag;
5223 int flag;
5224};
5225enum {
5226 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005227# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005228 FLAG_IF = (1 << RES_IF ),
5229 FLAG_THEN = (1 << RES_THEN ),
5230 FLAG_ELIF = (1 << RES_ELIF ),
5231 FLAG_ELSE = (1 << RES_ELSE ),
5232 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005233# endif
5234# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005235 FLAG_FOR = (1 << RES_FOR ),
5236 FLAG_WHILE = (1 << RES_WHILE),
5237 FLAG_UNTIL = (1 << RES_UNTIL),
5238 FLAG_DO = (1 << RES_DO ),
5239 FLAG_DONE = (1 << RES_DONE ),
5240 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005241# endif
5242# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005243 FLAG_MATCH = (1 << RES_MATCH),
5244 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005245# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005246 FLAG_START = (1 << RES_XXXX ),
5247};
5248
5249static const struct reserved_combo* match_reserved_word(o_string *word)
5250{
Eric Andersen25f27032001-04-26 23:22:31 +00005251 /* Mostly a list of accepted follow-up reserved words.
5252 * FLAG_END means we are done with the sequence, and are ready
5253 * to turn the compound list into a command.
5254 * FLAG_START means the word must start a new compound list.
5255 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005256 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005257# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005258 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5259 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5260 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5261 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5262 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5263 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005264# endif
5265# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005266 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5267 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5268 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5269 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5270 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5271 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005272# endif
5273# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005274 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5275 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005276# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005277 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005278 const struct reserved_combo *r;
5279
5280 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5281 if (strcmp(word->data, r->literal) == 0)
5282 return r;
5283 }
5284 return NULL;
5285}
Denis Vlasenkobb929512009-04-16 10:59:40 +00005286/* Return 0: not a keyword, 1: keyword
5287 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005288static int reserved_word(o_string *word, struct parse_context *ctx)
5289{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005290# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005291 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005292 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005293 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005294# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005295 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005296
Denis Vlasenkobb929512009-04-16 10:59:40 +00005297 if (word->o_quoted)
5298 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005299 r = match_reserved_word(word);
5300 if (!r)
5301 return 0;
5302
5303 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005304# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005305 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5306 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005307 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005308 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005309# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005310 if (r->flag == 0) { /* '!' */
5311 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005312 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00005313 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00005314 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005315 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005316 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005317 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005318 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005319 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005320
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005321 old = xmalloc(sizeof(*old));
5322 debug_printf_parse("push stack %p\n", old);
5323 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005324 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005325 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005326 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005327 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005328 ctx->ctx_res_w = RES_SNTX;
5329 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005330 } else {
5331 /* "{...} fi" is ok. "{...} if" is not
5332 * Example:
5333 * if { echo foo; } then { echo bar; } fi */
5334 if (ctx->command->group)
5335 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005336 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00005337
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005338 ctx->ctx_res_w = r->res;
5339 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005340 word->o_assignment = r->assignment_flag;
5341
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005342 if (ctx->old_flag & FLAG_END) {
5343 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005344
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005345 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005346 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005347 old = ctx->stack;
5348 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005349 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005350# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005351 o_addstr(&old->as_string, ctx->as_string.data);
5352 o_free_unsafe(&ctx->as_string);
5353 old->command->group_as_string = xstrdup(old->as_string.data);
5354 debug_printf_parse("pop, remembering as:'%s'\n",
5355 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005356# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005357 *ctx = *old; /* physical copy */
5358 free(old);
5359 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005360 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005361}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005362#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00005363
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005364/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005365 * Normal return is 0. Syntax errors return 1.
5366 * Note: on return, word is reset, but not o_free'd!
5367 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005368static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005369{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005370 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00005371
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005372 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005373 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005374 debug_printf_parse("done_word return 0: true null, ignored\n");
5375 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005376 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005377
Eric Andersen25f27032001-04-26 23:22:31 +00005378 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005379 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5380 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005381 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5382 * "2.7 Redirection
5383 * ...the word that follows the redirection operator
5384 * shall be subjected to tilde expansion, parameter expansion,
5385 * command substitution, arithmetic expansion, and quote
5386 * removal. Pathname expansion shall not be performed
5387 * on the word by a non-interactive shell; an interactive
5388 * shell may perform it, but shall do so only when
5389 * the expansion would result in one word."
5390 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005391 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005392 /* Cater for >\file case:
5393 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5394 * Same with heredocs:
5395 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5396 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005397 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5398 unbackslash(ctx->pending_redirect->rd_filename);
5399 /* Is it <<"HEREDOC"? */
5400 if (word->o_quoted) {
5401 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5402 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005403 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005404 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005405 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00005406 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005407 /* If this word wasn't an assignment, next ones definitely
5408 * can't be assignments. Even if they look like ones. */
5409 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5410 && word->o_assignment != WORD_IS_KEYWORD
5411 ) {
5412 word->o_assignment = NOT_ASSIGNMENT;
5413 } else {
5414 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5415 command->assignment_cnt++;
5416 word->o_assignment = MAYBE_ASSIGNMENT;
5417 }
5418
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005419#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005420# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00005421 if (ctx->ctx_dsemicolon
5422 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5423 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00005424 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005425 /* ctx->ctx_res_w = RES_MATCH; */
5426 ctx->ctx_dsemicolon = 0;
5427 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005428# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005429 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005430# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005431 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5432 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005433# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005434# if ENABLE_HUSH_CASE
5435 && ctx->ctx_res_w != RES_CASE
5436# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005437 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005438 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005439 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005440 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005441 debug_printf_parse("done_word return %d\n",
5442 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005443 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005444 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005445# ifdef CMD_SINGLEWORD_NOGLOB_COND
5446 if (strcmp(word->data, "export") == 0
5447# if ENABLE_HUSH_LOCAL
5448 || strcmp(word->data, "local") == 0
5449# endif
5450 ) {
5451 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5452 } else
5453# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005454# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005455 if (strcmp(word->data, "[[") == 0) {
5456 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5457 }
5458 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005459# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005460 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005461#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005462 if (command->group) {
5463 /* "{ echo foo; } echo bar" - bad */
5464 syntax_error_at(word->data);
5465 debug_printf_parse("done_word return 1: syntax error, "
5466 "groups and arglists don't mix\n");
5467 return 1;
5468 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005469 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005470 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5471 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005472 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005473 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005474 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005475 char *p = word->data;
5476 while (p[0] == SPECIAL_VAR_SYMBOL
5477 && (p[1] & 0x7f) == '@'
5478 && p[2] == SPECIAL_VAR_SYMBOL
5479 ) {
5480 p += 3;
5481 }
5482 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005483 /* saw no "$@", or not only "$@" but some
5484 * real text is there too */
5485 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005486 * e.g. "", $empty"" etc to not disappear */
5487 o_addchr(word, SPECIAL_VAR_SYMBOL);
5488 o_addchr(word, SPECIAL_VAR_SYMBOL);
5489 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005490 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005491 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005492 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005493 }
Eric Andersen25f27032001-04-26 23:22:31 +00005494
Denis Vlasenko06810332007-05-21 23:30:54 +00005495#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005496 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005497 if (word->o_quoted
5498 || !is_well_formed_var_name(command->argv[0], '\0')
5499 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005500 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005501 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005502 return 1;
5503 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005504 /* Force FOR to have just one word (variable name) */
5505 /* NB: basically, this makes hush see "for v in ..."
5506 * syntax as if it is "for v; in ...". FOR and IN become
5507 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005508 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005509 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005510#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005511#if ENABLE_HUSH_CASE
5512 /* Force CASE to have just one word */
5513 if (ctx->ctx_res_w == RES_CASE) {
5514 done_pipe(ctx, PIPE_SEQ);
5515 }
5516#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005517
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005518 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005519
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005520 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005521 return 0;
5522}
5523
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005524
5525/* Peek ahead in the input to find out if we have a "&n" construct,
5526 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005527 * Return:
5528 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5529 * REDIRFD_SYNTAX_ERR if syntax error,
5530 * REDIRFD_TO_FILE if no & was seen,
5531 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005532 */
5533#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005534#define parse_redir_right_fd(as_string, input) \
5535 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005536#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005537static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005538{
5539 int ch, d, ok;
5540
5541 ch = i_peek(input);
5542 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005543 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005544
5545 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005546 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005547 ch = i_peek(input);
5548 if (ch == '-') {
5549 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005550 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005551 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005552 }
5553 d = 0;
5554 ok = 0;
5555 while (ch != EOF && isdigit(ch)) {
5556 d = d*10 + (ch-'0');
5557 ok = 1;
5558 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005559 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005560 ch = i_peek(input);
5561 }
5562 if (ok) return d;
5563
5564//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5565
5566 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005567 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005568}
5569
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005570/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005571 */
5572static int parse_redirect(struct parse_context *ctx,
5573 int fd,
5574 redir_type style,
5575 struct in_str *input)
5576{
5577 struct command *command = ctx->command;
5578 struct redir_struct *redir;
5579 struct redir_struct **redirp;
5580 int dup_num;
5581
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005582 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005583 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005584 /* Check for a '>&1' type redirect */
5585 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5586 if (dup_num == REDIRFD_SYNTAX_ERR)
5587 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005588 } else {
5589 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005590 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005591 if (dup_num) { /* <<-... */
5592 ch = i_getch(input);
5593 nommu_addchr(&ctx->as_string, ch);
5594 ch = i_peek(input);
5595 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005596 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005597
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005598 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005599 int ch = i_peek(input);
5600 if (ch == '|') {
5601 /* >|FILE redirect ("clobbering" >).
5602 * Since we do not support "set -o noclobber" yet,
5603 * >| and > are the same for now. Just eat |.
5604 */
5605 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005606 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005607 }
5608 }
5609
5610 /* Create a new redir_struct and append it to the linked list */
5611 redirp = &command->redirects;
5612 while ((redir = *redirp) != NULL) {
5613 redirp = &(redir->next);
5614 }
5615 *redirp = redir = xzalloc(sizeof(*redir));
5616 /* redir->next = NULL; */
5617 /* redir->rd_filename = NULL; */
5618 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005619 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005620
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005621 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5622 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005623
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005624 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005625 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005626 /* Erik had a check here that the file descriptor in question
5627 * is legit; I postpone that to "run time"
5628 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005629 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5630 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005631 } else {
5632 /* Set ctx->pending_redirect, so we know what to do at the
5633 * end of the next parsed word. */
5634 ctx->pending_redirect = redir;
5635 }
5636 return 0;
5637}
5638
Eric Andersen25f27032001-04-26 23:22:31 +00005639/* If a redirect is immediately preceded by a number, that number is
5640 * supposed to tell which file descriptor to redirect. This routine
5641 * looks for such preceding numbers. In an ideal world this routine
5642 * needs to handle all the following classes of redirects...
5643 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5644 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5645 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5646 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005647 *
5648 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5649 * "2.7 Redirection
5650 * ... If n is quoted, the number shall not be recognized as part of
5651 * the redirection expression. For example:
5652 * echo \2>a
5653 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005654 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005655 *
5656 * A -1 return means no valid number was found,
5657 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005658 */
5659static int redirect_opt_num(o_string *o)
5660{
5661 int num;
5662
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005663 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005664 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005665 num = bb_strtou(o->data, NULL, 10);
5666 if (errno || num < 0)
5667 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005668 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005669 return num;
5670}
5671
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005672#if BB_MMU
5673#define fetch_till_str(as_string, input, word, skip_tabs) \
5674 fetch_till_str(input, word, skip_tabs)
5675#endif
5676static char *fetch_till_str(o_string *as_string,
5677 struct in_str *input,
5678 const char *word,
5679 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005680{
5681 o_string heredoc = NULL_O_STRING;
5682 int past_EOL = 0;
5683 int ch;
5684
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005685 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005686 while (1) {
5687 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005688 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005689 if (ch == '\n') {
5690 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5691 heredoc.data[past_EOL] = '\0';
5692 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5693 return heredoc.data;
5694 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005695 do {
5696 o_addchr(&heredoc, ch);
5697 past_EOL = heredoc.length;
5698 jump_in:
5699 do {
5700 ch = i_getch(input);
5701 nommu_addchr(as_string, ch);
5702 } while (skip_tabs && ch == '\t');
5703 } while (ch == '\n');
5704 }
5705 if (ch == EOF) {
5706 o_free_unsafe(&heredoc);
5707 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005708 }
5709 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005710 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005711 }
5712}
5713
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005714/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5715 * and load them all. There should be exactly heredoc_cnt of them.
5716 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005717static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5718{
5719 struct pipe *pi = ctx->list_head;
5720
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005721 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005722 int i;
5723 struct command *cmd = pi->cmds;
5724
5725 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5726 pi->num_cmds,
5727 cmd->argv ? cmd->argv[0] : "NONE");
5728 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005729 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005730
5731 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5732 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005733 while (redir) {
5734 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005735 char *p;
5736
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005737 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005738 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005739 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005740 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005741 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005742 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005743 return 1;
5744 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005745 free(redir->rd_filename);
5746 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005747 heredoc_cnt--;
5748 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005749 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005750 }
5751 cmd++;
5752 }
5753 pi = pi->next;
5754 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005755#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005756 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005757 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005758 bb_error_msg_and_die("heredoc BUG 2");
5759#endif
5760 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005761}
5762
5763
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005764#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005765static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005766{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005767 pid_t pid;
5768 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005769# if !BB_MMU
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01005770 char **to_free = NULL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005771# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005772
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005773 xpipe(channel);
Pascal Bellard926031b2010-07-04 15:32:38 +02005774 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko05743d72008-02-10 12:10:08 +00005775 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005776 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005777 /* Process substitution is not considered to be usual
5778 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005779 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5780 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005781 bb_signals(0
5782 + (1 << SIGTSTP)
5783 + (1 << SIGTTIN)
5784 + (1 << SIGTTOU)
5785 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005786 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005787 close(channel[0]); /* NB: close _first_, then move fd! */
5788 xmove_fd(channel[1], 1);
5789 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005790 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005791 /* Awful hack for `trap` or $(trap).
5792 *
5793 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5794 * contains an example where "trap" is executed in a subshell:
5795 *
5796 * save_traps=$(trap)
5797 * ...
5798 * eval "$save_traps"
5799 *
5800 * Standard does not say that "trap" in subshell shall print
5801 * parent shell's traps. It only says that its output
5802 * must have suitable form, but then, in the above example
5803 * (which is not supposed to be normative), it implies that.
5804 *
5805 * bash (and probably other shell) does implement it
5806 * (traps are reset to defaults, but "trap" still shows them),
5807 * but as a result, "trap" logic is hopelessly messed up:
5808 *
5809 * # trap
5810 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5811 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5812 * # true | trap <--- trap is in subshell - no output (ditto)
5813 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5814 * trap -- 'echo Ho' SIGWINCH
5815 * # echo `(trap)` <--- in subshell in subshell - output
5816 * trap -- 'echo Ho' SIGWINCH
5817 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5818 * trap -- 'echo Ho' SIGWINCH
5819 *
5820 * The rules when to forget and when to not forget traps
5821 * get really complex and nonsensical.
5822 *
5823 * Our solution: ONLY bare $(trap) or `trap` is special.
5824 */
5825 s = skip_whitespace(s);
5826 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5827 {
5828 static const char *const argv[] = { NULL, NULL };
5829 builtin_trap((char**)argv);
5830 exit(0); /* not _exit() - we need to fflush */
5831 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005832# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005833 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005834 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005835 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005836# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005837 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005838 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5839 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005840 * echo OK
5841 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005842 re_execute_shell(&to_free,
5843 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005844 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005845 G.global_argv + 1,
5846 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005847# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005848 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005849
5850 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005851 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005852# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005853 G.count_SIGCHLD++;
5854//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 +02005855# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005856 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005857# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005858 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005859# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005860 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005861 close_on_exec_on(channel[0]);
5862 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005863}
5864
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005865/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005866static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005867{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005868 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005869 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005870 pid_t pid;
5871 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005872
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005873 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005874
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005875 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005876 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005877 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005878 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005879 if (ch == '\n') {
5880 eol_cnt++;
5881 continue;
5882 }
5883 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005884 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005885 eol_cnt--;
5886 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005887 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005888 }
5889
Denys Vlasenko647553a2009-11-15 19:58:19 +01005890 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005891 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005892 /* We need to extract exitcode. Test case
5893 * "true; echo `sleep 1; false` $?"
5894 * should print 1 */
5895 safe_waitpid(pid, &status, 0);
5896 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5897 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005898}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005899#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005900
Denys Vlasenkoc2704542009-11-20 19:14:19 +01005901#if !ENABLE_HUSH_FUNCTIONS
5902#define parse_group(dest, ctx, input, ch) \
5903 parse_group(ctx, input, ch)
5904#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005905static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005906 struct in_str *input, int ch)
5907{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005908 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005909 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005910 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005911 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005912 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005913 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005914
5915 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005916#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005917 if (ch == '(' && !dest->o_quoted) {
5918 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005919 if (done_word(dest, ctx))
5920 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005921 if (!command->argv)
5922 goto skip; /* (... */
5923 if (command->argv[1]) { /* word word ... (... */
5924 syntax_error_unexpected_ch('(');
5925 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005926 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005927 /* it is "word(..." or "word (..." */
5928 do
5929 ch = i_getch(input);
5930 while (ch == ' ' || ch == '\t');
5931 if (ch != ')') {
5932 syntax_error_unexpected_ch(ch);
5933 return 1;
5934 }
5935 nommu_addchr(&ctx->as_string, ch);
5936 do
5937 ch = i_getch(input);
5938 while (ch == ' ' || ch == '\t' || ch == '\n');
5939 if (ch != '{') {
5940 syntax_error_unexpected_ch(ch);
5941 return 1;
5942 }
5943 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005944 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005945 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005946 }
5947#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005948
5949#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005950 if (command->argv /* word [word]{... */
5951 || dest->length /* word{... */
5952 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005953 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005954 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005955 debug_printf_parse("parse_group return 1: "
5956 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005957 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005958 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005959#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005960
5961#if ENABLE_HUSH_FUNCTIONS
5962 skip:
5963#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005964 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005965 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005966 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005967 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005968 } else {
5969 /* bash does not allow "{echo...", requires whitespace */
5970 ch = i_getch(input);
5971 if (ch != ' ' && ch != '\t' && ch != '\n') {
5972 syntax_error_unexpected_ch(ch);
5973 return 1;
5974 }
5975 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005976 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005977
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005978 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005979#if BB_MMU
5980# define as_string NULL
5981#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005982 char *as_string = NULL;
5983#endif
5984 pipe_list = parse_stream(&as_string, input, endch);
5985#if !BB_MMU
5986 if (as_string)
5987 o_addstr(&ctx->as_string, as_string);
5988#endif
5989 /* empty ()/{} or parse error? */
5990 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005991 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005992 if (!BB_MMU)
5993 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005994 debug_printf_parse("parse_group return 1: "
5995 "parse_stream returned %p\n", pipe_list);
5996 return 1;
5997 }
5998 command->group = pipe_list;
5999#if !BB_MMU
6000 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6001 command->group_as_string = as_string;
6002 debug_printf_parse("end of group, remembering as:'%s'\n",
6003 command->group_as_string);
6004#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006005#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006006 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006007 debug_printf_parse("parse_group return 0\n");
6008 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006009 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00006010}
6011
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006012#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006013/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006014static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006015/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006016static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006017{
6018 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006019 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006020 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006021 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006022 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006023 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006024 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006025 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006026 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006027 }
6028}
6029/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006030static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006031{
6032 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006033 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006034 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006035 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006036 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006037 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006038 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006039 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006040 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006041 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006042 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006043 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006044 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006045 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006046 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006047 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006048 continue;
6049 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00006050 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006051 }
6052}
6053/* Process `cmd` - copy contents until "`" is seen. Complicated by
6054 * \` quoting.
6055 * "Within the backquoted style of command substitution, backslash
6056 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6057 * The search for the matching backquote shall be satisfied by the first
6058 * backquote found without a preceding backslash; during this search,
6059 * if a non-escaped backquote is encountered within a shell comment,
6060 * a here-document, an embedded command substitution of the $(command)
6061 * form, or a quoted string, undefined results occur. A single-quoted
6062 * or double-quoted string that begins, but does not end, within the
6063 * "`...`" sequence produces undefined results."
6064 * Example Output
6065 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6066 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006067static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006068{
6069 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006070 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006071 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006072 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006073 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006074 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006075 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006076 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006077 if (ch == '\\') {
6078 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006079 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006080 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006081 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006082 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006083 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006084 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006085 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006086 ch = ch2;
6087 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006088 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006089 }
6090}
6091/* Process $(cmd) - copy contents until ")" is seen. Complicated by
6092 * quoting and nested ()s.
6093 * "With the $(command) style of command substitution, all characters
6094 * following the open parenthesis to the matching closing parenthesis
6095 * constitute the command. Any valid shell script can be used for command,
6096 * except a script consisting solely of redirections which produces
6097 * unspecified results."
6098 * Example Output
6099 * echo $(echo '(TEST)' BEST) (TEST) BEST
6100 * echo $(echo 'TEST)' BEST) TEST) BEST
6101 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02006102 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006103 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006104 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006105 * In bash compat mode, it needs to also be able to stop on '}' or ':'
6106 * for ${var:N[:M]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006107 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006108#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006109static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006110{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006111 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02006112 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006113# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006114 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006115# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006116 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6117
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006118 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006119 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006120 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006121 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006122 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006123 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006124 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006125 if (!dbl)
6126 break;
6127 /* we look for closing )) of $((EXPR)) */
6128 if (i_peek(input) == end_ch) {
6129 i_getch(input); /* eat second ')' */
6130 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006131 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006132 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006133 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006134 if (ch == '(' || ch == '{') {
6135 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006136 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006137 o_addchr(dest, ch);
6138 continue;
6139 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006140 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006141 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006142 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006143 continue;
6144 }
6145 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006146 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006147 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006148 continue;
6149 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006150 if (ch == '`') {
6151 add_till_backquote(dest, input);
6152 o_addchr(dest, ch);
6153 continue;
6154 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006155 if (ch == '\\') {
6156 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006157 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006158 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006159 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006160 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006161 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006162 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006163 continue;
6164 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006165 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006166 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006167}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006168#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006169
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006170/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006171#if BB_MMU
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006172#define parse_dollar(as_string, dest, input) \
6173 parse_dollar(dest, input)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006174#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006175#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006176static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006177 o_string *dest,
6178 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00006179{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006180 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006181 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006182
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006183 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006184 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006185 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006186 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00006187 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006188 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006189 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006190 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006191 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006192 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006193 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006194 if (!isalnum(ch) && ch != '_')
6195 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006196 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006197 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006198 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006199 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006200 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006201 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006202 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006203 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006204 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006205 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006206 o_addchr(dest, ch | quote_mask);
6207 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006208 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006209 case '$': /* pid */
6210 case '!': /* last bg pid */
6211 case '?': /* last exit code */
6212 case '#': /* number of args */
6213 case '*': /* args */
6214 case '@': /* args */
6215 goto make_one_char_var;
6216 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04006217 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6218
Denys Vlasenko74369502010-05-21 19:52:01 +02006219 ch = i_getch(input); /* eat '{' */
6220 nommu_addchr(as_string, ch);
6221
6222 ch = i_getch(input); /* first char after '{' */
6223 nommu_addchr(as_string, ch);
6224 /* It should be ${?}, or ${#var},
6225 * or even ${?+subst} - operator acting on a special variable,
6226 * or the beginning of variable name.
6227 */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02006228 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
Denys Vlasenko74369502010-05-21 19:52:01 +02006229 bad_dollar_syntax:
6230 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006231 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02006232 return 1;
6233 }
6234 ch |= quote_mask;
6235
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006236 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02006237 * However, this regresses some of our testsuite cases
6238 * which check invalid constructs like ${%}.
6239 * Oh well... let's check that the var name part is fine... */
6240
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006241 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006242 unsigned pos;
6243
Denys Vlasenko74369502010-05-21 19:52:01 +02006244 o_addchr(dest, ch);
6245 debug_printf_parse(": '%c'\n", ch);
6246
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006247 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006248 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02006249 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00006250 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006251
Denys Vlasenko74369502010-05-21 19:52:01 +02006252 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006253 unsigned end_ch;
6254 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006255 /* handle parameter expansions
6256 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6257 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006258 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6259 goto bad_dollar_syntax;
Denys Vlasenko74369502010-05-21 19:52:01 +02006260 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006261
6262 /* Eat everything until closing '}' (or ':') */
6263 end_ch = '}';
6264 if (ENABLE_HUSH_BASH_COMPAT
6265 && ch == ':'
6266 && !strchr("%#:-=+?"+3, i_peek(input))
6267 ) {
6268 /* It's ${var:N[:M]} thing */
6269 end_ch = '}' * 0x100 + ':';
6270 }
6271 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006272 if (!BB_MMU)
6273 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006274#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006275 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006276#else
6277#error Simple code to only allow ${var} is not implemented
6278#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006279 if (as_string) {
6280 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006281 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006282 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006283
6284 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6285 /* close the first block: */
6286 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6287 /* while parsing N from ${var:N[:M]}... */
6288 if ((end_ch & 0xff) == last_ch) {
6289 /* ...got ':' - parse the rest */
6290 end_ch = '}';
6291 goto again;
6292 }
6293 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6294 o_addstr(dest, "999999999");
6295 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006296 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006297 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006298 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006299 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6300 break;
6301 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006302#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006303 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006304 unsigned pos;
6305
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006306 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006307 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006308# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006309 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006310 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006311 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006312 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6313 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006314 if (!BB_MMU)
6315 pos = dest->length;
6316 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006317 if (as_string) {
6318 o_addstr(as_string, dest->data + pos);
6319 o_addchr(as_string, ')');
6320 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006321 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006322 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006323 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006324 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006325# endif
6326# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006327 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6328 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006329 if (!BB_MMU)
6330 pos = dest->length;
6331 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006332 if (as_string) {
6333 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006334 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006335 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006336 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006337# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006338 break;
6339 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006340#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006341 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006342 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006343 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006344 ch = i_peek(input);
6345 if (isalnum(ch)) { /* it's $_name or $_123 */
6346 ch = '_';
6347 goto make_var;
6348 }
6349 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02006350 /* TODO: $_ and $-: */
6351 /* $_ Shell or shell script name; or last argument of last command
6352 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6353 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006354 /* $- Option flags set by set builtin or shell options (-i etc) */
6355 default:
6356 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00006357 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006358 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00006359 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006360#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00006361}
6362
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006363#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006364#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006365 parse_stream_dquoted(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006366#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006367#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006368static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006369 o_string *dest,
6370 struct in_str *input,
6371 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006372{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006373 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006374 int next;
6375
6376 again:
6377 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006378 if (ch != EOF)
6379 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006380 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006381 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006382 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006383 debug_printf_parse("parse_stream_dquoted return 0\n");
6384 return 0;
6385 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006386 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006387 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006388 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006389 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006390 }
6391 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006392 if (ch != '\n') {
6393 next = i_peek(input);
6394 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006395 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006396 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006397 if (ch == '\\') {
6398 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006399 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006400 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006401 }
6402 /* bash:
6403 * "The backslash retains its special meaning [in "..."]
6404 * only when followed by one of the following characters:
6405 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006406 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006407 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006408 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00006409 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006410 if (ch != '\n') {
6411 o_addqchr(dest, ch);
6412 nommu_addchr(as_string, ch);
6413 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006414 } else {
6415 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00006416 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006417 }
6418 goto again;
6419 }
6420 if (ch == '$') {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006421 if (parse_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006422 debug_printf_parse("parse_stream_dquoted return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006423 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006424 return 1;
6425 }
6426 goto again;
6427 }
6428#if ENABLE_HUSH_TICK
6429 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006430 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006431 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6432 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006433 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006434 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6435 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00006436 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006437 }
6438#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00006439 o_addQchr(dest, ch);
6440 if (ch == '='
6441 && (dest->o_assignment == MAYBE_ASSIGNMENT
6442 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006443 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00006444 ) {
6445 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6446 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006447 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006448#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006449}
6450
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006451/*
6452 * Scan input until EOF or end_trigger char.
6453 * Return a list of pipes to execute, or NULL on EOF
6454 * or if end_trigger character is met.
6455 * On syntax error, exit is shell is not interactive,
6456 * reset parsing machinery and start parsing anew,
6457 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006458 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006459static struct pipe *parse_stream(char **pstring,
6460 struct in_str *input,
6461 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006462{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006463 struct parse_context ctx;
6464 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006465 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006466 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006467
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006468 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006469 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006470 * found. When recursing, quote state is passed in via dest->o_escape.
6471 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006472 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006473 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006474 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006475
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006476 /* If very first arg is "" or '', dest.data may end up NULL.
6477 * Preventing this: */
6478 o_addchr(&dest, '\0');
6479 dest.length = 0;
6480
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006481 G.ifs = get_local_var_value("IFS");
6482 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01006483 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006484
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006485 reset:
6486#if ENABLE_HUSH_INTERACTIVE
6487 input->promptmode = 0; /* PS1 */
6488#endif
6489 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6490 initialize_context(&ctx);
6491 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006492 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006493 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006494 const char *is_ifs;
6495 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006496 int ch;
6497 int next;
6498 int redir_fd;
6499 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006500
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006501 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006502 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006503 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006504 goto parse_error;
6505 }
6506 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006507 is_in_dquote = 0;
6508 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006509 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006510 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6511 ch, ch, dest.o_escape);
6512 if (ch == EOF) {
6513 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006514
6515 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006516 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006517 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006518 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006519 /* end_trigger == '}' case errors out earlier,
6520 * checking only ')' */
6521 if (end_trigger == ')') {
6522 syntax_error_unterm_ch('('); /* exits */
6523 /* goto parse_error; */
6524 }
6525
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006526 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006527 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006528 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006529 o_free(&dest);
6530 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006531 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006532 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006533 /* (this makes bare "&" cmd a no-op.
6534 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006535 if (pi->num_cmds == 0
6536 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6537 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006538 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006539 pi = NULL;
6540 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006541#if !BB_MMU
6542 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6543 if (pstring)
6544 *pstring = ctx.as_string.data;
6545 else
6546 o_free_unsafe(&ctx.as_string);
6547#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006548 debug_leave();
6549 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006550 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006551 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006552 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006553
6554 next = '\0';
6555 if (ch != '\n')
6556 next = i_peek(input);
6557
6558 is_special = "{}<>;&|()#'" /* special outside of "str" */
6559 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6560 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02006561 if (ctx.command->argv /* word [word]{... - non-special */
6562 || dest.length /* word{... - non-special */
6563 || dest.o_quoted /* ""{... - non-special */
6564 || (next != ';' /* }; - special */
6565 && next != ')' /* }) - special */
6566 && next != '&' /* }& and }&& ... - special */
6567 && next != '|' /* }|| ... - special */
6568 && !strchr(G.ifs, next) /* {word - non-special */
6569 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006570 ) {
6571 /* They are not special, skip "{}" */
6572 is_special += 2;
6573 }
6574 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006575 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006576
6577 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006578 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006579 o_addQchr(&dest, ch);
6580 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6581 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006582 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006583 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006584 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006585 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006586 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006587 continue;
6588 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006589
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006590 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006591 if (done_word(&dest, &ctx)) {
6592 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006593 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006594 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006595#if ENABLE_HUSH_CASE
6596 /* "case ... in <newline> word) ..." -
6597 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006598 if (ctx.command->argv == NULL
6599 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006600 ) {
6601 continue;
6602 }
6603#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006604 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006605 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006606 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6607 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006608 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006609 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006610 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006611 heredoc_cnt = 0;
6612 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006613 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006614 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006615 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006616 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006617 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006618 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006619
6620 /* "cmd}" or "cmd }..." without semicolon or &:
6621 * } is an ordinary char in this case, even inside { cmd; }
6622 * Pathological example: { ""}; } should exec "}" cmd
6623 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006624 if (ch == '}') {
6625 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6626 || dest.length != 0 /* word} */
6627 || dest.o_quoted /* ""} */
6628 ) {
6629 goto ordinary_char;
6630 }
6631 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6632 goto skip_end_trigger;
6633 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006634 }
6635
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006636 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006637 && (ch != ';' || heredoc_cnt == 0)
6638#if ENABLE_HUSH_CASE
6639 && (ch != ')'
6640 || ctx.ctx_res_w != RES_MATCH
6641 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6642 )
6643#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006644 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006645 if (heredoc_cnt) {
6646 /* This is technically valid:
6647 * { cat <<HERE; }; echo Ok
6648 * heredoc
6649 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006650 * HERE
6651 * but we don't support this.
6652 * We require heredoc to be in enclosing {}/(),
6653 * if any.
6654 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006655 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006656 goto parse_error;
6657 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006658 if (done_word(&dest, &ctx)) {
6659 goto parse_error;
6660 }
6661 done_pipe(&ctx, PIPE_SEQ);
6662 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006663 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006664 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006665 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006666 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006667 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006668#if !BB_MMU
6669 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6670 if (pstring)
6671 *pstring = ctx.as_string.data;
6672 else
6673 o_free_unsafe(&ctx.as_string);
6674#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006675 debug_leave();
6676 debug_printf_parse("parse_stream return %p: "
6677 "end_trigger char found\n",
6678 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006679 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006680 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006681 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006682 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006683 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006684 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006685
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006686 /* Catch <, > before deciding whether this word is
6687 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6688 switch (ch) {
6689 case '>':
6690 redir_fd = redirect_opt_num(&dest);
6691 if (done_word(&dest, &ctx)) {
6692 goto parse_error;
6693 }
6694 redir_style = REDIRECT_OVERWRITE;
6695 if (next == '>') {
6696 redir_style = REDIRECT_APPEND;
6697 ch = i_getch(input);
6698 nommu_addchr(&ctx.as_string, ch);
6699 }
6700#if 0
6701 else if (next == '(') {
6702 syntax_error(">(process) not supported");
6703 goto parse_error;
6704 }
6705#endif
6706 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6707 goto parse_error;
6708 continue; /* back to top of while (1) */
6709 case '<':
6710 redir_fd = redirect_opt_num(&dest);
6711 if (done_word(&dest, &ctx)) {
6712 goto parse_error;
6713 }
6714 redir_style = REDIRECT_INPUT;
6715 if (next == '<') {
6716 redir_style = REDIRECT_HEREDOC;
6717 heredoc_cnt++;
6718 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6719 ch = i_getch(input);
6720 nommu_addchr(&ctx.as_string, ch);
6721 } else if (next == '>') {
6722 redir_style = REDIRECT_IO;
6723 ch = i_getch(input);
6724 nommu_addchr(&ctx.as_string, ch);
6725 }
6726#if 0
6727 else if (next == '(') {
6728 syntax_error("<(process) not supported");
6729 goto parse_error;
6730 }
6731#endif
6732 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6733 goto parse_error;
6734 continue; /* back to top of while (1) */
6735 }
6736
6737 if (dest.o_assignment == MAYBE_ASSIGNMENT
6738 /* check that we are not in word in "a=1 2>word b=1": */
6739 && !ctx.pending_redirect
6740 ) {
6741 /* ch is a special char and thus this word
6742 * cannot be an assignment */
6743 dest.o_assignment = NOT_ASSIGNMENT;
6744 }
6745
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006746 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6747
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006748 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006749 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006750 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006751 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006752 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006753 if (ch == EOF || ch == '\n')
6754 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006755 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006756 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006757 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006758 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006759 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006760 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006761 }
6762 break;
6763 case '\\':
6764 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006765 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006766 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006767 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006768 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006769 if (ch != '\n') {
6770 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006771 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006772 o_addchr(&dest, ch);
6773 nommu_addchr(&ctx.as_string, ch);
6774 /* Example: echo Hello \2>file
6775 * we need to know that word 2 is quoted */
6776 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006777 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006778#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006779 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006780 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6781 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006782 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006783#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006784 break;
6785 case '$':
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006786 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006787 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006788 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006789 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006790 }
Eric Andersen25f27032001-04-26 23:22:31 +00006791 break;
6792 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006793 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006794 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006795 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006796 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006797 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006798 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006799 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006800 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006801 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006802 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006803 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006804 }
Eric Andersen25f27032001-04-26 23:22:31 +00006805 break;
6806 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006807 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006808 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006809 if (dest.o_assignment == NOT_ASSIGNMENT)
6810 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006811 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006812#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006813 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006814 unsigned pos;
6815
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006816 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6817 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006818 pos = dest.length;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006819 add_till_backquote(&dest, input);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006820# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006821 o_addstr(&ctx.as_string, dest.data + pos);
6822 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006823# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006824 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6825 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006826 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006827 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006828#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006829 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006830#if ENABLE_HUSH_CASE
6831 case_semi:
6832#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006833 if (done_word(&dest, &ctx)) {
6834 goto parse_error;
6835 }
6836 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006837#if ENABLE_HUSH_CASE
6838 /* Eat multiple semicolons, detect
6839 * whether it means something special */
6840 while (1) {
6841 ch = i_peek(input);
6842 if (ch != ';')
6843 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006844 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006845 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006846 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006847 ctx.ctx_dsemicolon = 1;
6848 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006849 break;
6850 }
6851 }
6852#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006853 new_cmd:
6854 /* We just finished a cmd. New one may start
6855 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006856 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006857 break;
6858 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006859 if (done_word(&dest, &ctx)) {
6860 goto parse_error;
6861 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006862 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006863 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006864 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006865 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006866 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006867 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006868 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006869 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006870 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006871 if (done_word(&dest, &ctx)) {
6872 goto parse_error;
6873 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006874#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006875 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006876 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006877#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006878 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006879 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006880 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006881 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006882 } else {
6883 /* we could pick up a file descriptor choice here
6884 * with redirect_opt_num(), but bash doesn't do it.
6885 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006886 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006887#if !BB_MMU
6888 o_reset_to_empty_unquoted(&ctx.as_string);
6889#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006890 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006891 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006892 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006893#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006894 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006895 if (ctx.ctx_res_w == RES_MATCH
6896 && ctx.command->argv == NULL /* not (word|(... */
6897 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006898 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006899 ) {
6900 continue;
6901 }
6902#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006903 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006904 if (parse_group(&dest, &ctx, input, ch) != 0) {
6905 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006906 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006907 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006908 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006909#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006910 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006911 goto case_semi;
6912#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006913 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006914 /* proper use of this character is caught by end_trigger:
6915 * if we see {, we call parse_group(..., end_trigger='}')
6916 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006917 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006918 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006919 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006920 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006921 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006922 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006923 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006924
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006925 parse_error:
6926 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006927 struct parse_context *pctx;
6928 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006929
6930 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006931 * Sample for finding leaks on syntax error recovery path.
6932 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006933 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006934 * Samples to catch leaks at execution:
6935 * while if (true | {true;}); then echo ok; fi; do break; done
6936 * 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 +00006937 */
6938 pctx = &ctx;
6939 do {
6940 /* Update pipe/command counts,
6941 * otherwise freeing may miss some */
6942 done_pipe(pctx, PIPE_SEQ);
6943 debug_printf_clean("freeing list %p from ctx %p\n",
6944 pctx->list_head, pctx);
6945 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006946 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006947 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006948#if !BB_MMU
6949 o_free_unsafe(&pctx->as_string);
6950#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006951 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006952 if (pctx != &ctx) {
6953 free(pctx);
6954 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006955 IF_HAS_KEYWORDS(pctx = p2;)
6956 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006957 /* Free text, clear all dest fields */
6958 o_free(&dest);
6959 /* If we are not in top-level parse, we return,
6960 * our caller will propagate error.
6961 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006962 if (end_trigger != ';') {
6963#if !BB_MMU
6964 if (pstring)
6965 *pstring = NULL;
6966#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006967 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006968 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006969 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006970 /* Discard cached input, force prompt */
6971 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006972 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006973 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006974 }
Eric Andersen25f27032001-04-26 23:22:31 +00006975}
6976
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006977/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006978 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6979 * end_trigger controls how often we stop parsing
6980 * NUL: parse all, execute, return
6981 * ';': parse till ';' or newline, execute, repeat till EOF
6982 */
6983static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006984{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006985 /* Why we need empty flag?
6986 * An obscure corner case "false; ``; echo $?":
6987 * empty command in `` should still set $? to 0.
6988 * But we can't just set $? to 0 at the start,
6989 * this breaks "false; echo `echo $?`" case.
6990 */
6991 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006992 while (1) {
6993 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006994
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006995 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006996 if (!pipe_list) { /* EOF */
6997 if (empty)
6998 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006999 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007000 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007001 debug_print_tree(pipe_list, 0);
7002 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7003 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007004 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007005 }
Eric Andersen25f27032001-04-26 23:22:31 +00007006}
7007
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007008static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007009{
7010 struct in_str input;
7011 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007012 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00007013}
7014
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007015static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00007016{
Eric Andersen25f27032001-04-26 23:22:31 +00007017 struct in_str input;
7018 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007019 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00007020}
7021
Denis Vlasenkof9375282009-04-05 19:13:39 +00007022/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007023static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007024{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007025 unsigned sig;
7026 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007027 sigset_t old_blocked_set;
7028
7029 if (!G.inherited_set_is_saved) {
7030 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7031 G.inherited_set = G.blocked_set;
7032 }
7033 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007034
Denis Vlasenkof9375282009-04-05 19:13:39 +00007035 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007036 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007037 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007038 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007039 mask |= SPECIAL_JOB_SIGS;
7040 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007041 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007042
Denis Vlasenkof9375282009-04-05 19:13:39 +00007043 sig = 0;
7044 while (mask) {
7045 if (mask & 1)
7046 sigaddset(&G.blocked_set, sig);
7047 mask >>= 1;
7048 sig++;
7049 }
7050 sigdelset(&G.blocked_set, SIGCHLD);
7051
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007052 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7053 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7054
Denis Vlasenkof9375282009-04-05 19:13:39 +00007055 /* POSIX allows shell to re-enable SIGCHLD
7056 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007057#if ENABLE_HUSH_FAST
7058 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007059 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007060 signal(SIGCHLD, SIGCHLD_handler);
7061#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007062 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007063 signal(SIGCHLD, SIG_DFL);
7064#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007065
7066 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007067}
7068
7069#if ENABLE_HUSH_JOB
7070/* helper */
7071static void maybe_set_to_sigexit(int sig)
7072{
7073 void (*handler)(int);
7074 /* non_DFL_mask'ed signals are, well, masked,
7075 * no need to set handler for them.
7076 */
7077 if (!((G.non_DFL_mask >> sig) & 1)) {
7078 handler = signal(sig, sigexit);
7079 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7080 signal(sig, handler);
7081 }
7082}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007083/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007084static void set_fatal_handlers(void)
7085{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007086 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007087 if (HUSH_DEBUG) {
7088 maybe_set_to_sigexit(SIGILL );
7089 maybe_set_to_sigexit(SIGFPE );
7090 maybe_set_to_sigexit(SIGBUS );
7091 maybe_set_to_sigexit(SIGSEGV);
7092 maybe_set_to_sigexit(SIGTRAP);
7093 } /* else: hush is perfect. what SEGV? */
7094 maybe_set_to_sigexit(SIGABRT);
7095 /* bash 3.2 seems to handle these just like 'fatal' ones */
7096 maybe_set_to_sigexit(SIGPIPE);
7097 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007098 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007099 * if we aren't interactive... but in this case
7100 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007101 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007102 /*maybe_set_to_sigexit(SIGTERM);*/
7103 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007104}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007105#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007106
Denis Vlasenkod5762932009-03-31 11:22:57 +00007107static int set_mode(const char cstate, const char mode)
7108{
7109 int state = (cstate == '-' ? 1 : 0);
7110 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007111 case 'n': G.n_mode = state; break;
7112 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007113 default: return EXIT_FAILURE;
7114 }
7115 return EXIT_SUCCESS;
7116}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007117
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007118int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007119int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007120{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007121 static const struct variable const_shell_ver = {
7122 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00007123 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007124 .max_len = 1, /* 0 can provoke free(name) */
7125 .flg_export = 1,
7126 .flg_read_only = 1,
7127 };
Eric Andersen25f27032001-04-26 23:22:31 +00007128 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007129 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007130 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007131 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00007132
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007133 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007134 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007135 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007136#if !BB_MMU
7137 G.argv0_for_re_execing = argv[0];
7138#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007139 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007140 G.shell_ver = const_shell_ver; /* copying struct here */
7141 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007142 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007143 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7144 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007145 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007146 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007147 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007148 if (e) while (*e) {
7149 char *value = strchr(*e, '=');
7150 if (value) { /* paranoia */
7151 cur_var->next = xzalloc(sizeof(*cur_var));
7152 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007153 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007154 cur_var->max_len = strlen(*e);
7155 cur_var->flg_export = 1;
7156 }
7157 e++;
7158 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007159 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007160 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007161 putenv((char *)hush_version_str);
7162
7163 /* Export PWD */
7164 set_pwd_var(/*exp:*/ 1);
7165 /* bash also exports SHLVL and _,
7166 * and sets (but doesn't export) the following variables:
7167 * BASH=/bin/bash
7168 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7169 * BASH_VERSION='3.2.0(1)-release'
7170 * HOSTTYPE=i386
7171 * MACHTYPE=i386-pc-linux-gnu
7172 * OSTYPE=linux-gnu
7173 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007174 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007175 * EUID=<NNNNN>
7176 * UID=<NNNNN>
7177 * GROUPS=()
7178 * LINES=<NNN>
7179 * COLUMNS=<NNN>
7180 * BASH_ARGC=()
7181 * BASH_ARGV=()
7182 * BASH_LINENO=()
7183 * BASH_SOURCE=()
7184 * DIRSTACK=()
7185 * PIPESTATUS=([0]="0")
7186 * HISTFILE=/<xxx>/.bash_history
7187 * HISTFILESIZE=500
7188 * HISTSIZE=500
7189 * MAILCHECK=60
7190 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7191 * SHELL=/bin/bash
7192 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7193 * TERM=dumb
7194 * OPTERR=1
7195 * OPTIND=1
7196 * IFS=$' \t\n'
7197 * PS1='\s-\v\$ '
7198 * PS2='> '
7199 * PS4='+ '
7200 */
7201
Denis Vlasenko38f63192007-01-22 09:03:07 +00007202#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007203 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007204#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007205 G.global_argc = argc;
7206 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007207 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007208 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007209
Denis Vlasenkoed782372009-04-10 00:45:02 +00007210 if (setjmp(die_jmp)) {
7211 /* xfunc has failed! die die die */
7212 /* no EXIT traps, this is an escape hatch! */
7213 G.exiting = 1;
7214 hush_exit(xfunc_error_retval);
7215 }
7216
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007217 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007218 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007219 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007220 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007221 * in order to intercept (more) signals.
7222 */
7223
7224 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007225 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007226 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007227 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007228 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007229#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007230 "<:$:R:V:"
7231# if ENABLE_HUSH_FUNCTIONS
7232 "F:"
7233# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007234#endif
7235 );
7236 if (opt <= 0)
7237 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007238 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007239 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007240 /* Possibilities:
7241 * sh ... -c 'script'
7242 * sh ... -c 'script' ARG0 [ARG1...]
7243 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007244 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007245 * "" needs to be replaced with NULL
7246 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007247 * Note: the form without ARG0 never happens:
7248 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007249 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007250 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007251 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007252 G.root_ppid = getppid();
7253 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007254 G.global_argv = argv + optind;
7255 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007256 if (builtin_argc) {
7257 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7258 const struct built_in_command *x;
7259
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007260 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007261 x = find_builtin(optarg);
7262 if (x) { /* paranoia */
7263 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7264 G.global_argv += builtin_argc;
7265 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007266 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007267 }
7268 goto final_return;
7269 }
7270 if (!G.global_argv[0]) {
7271 /* -c 'script' (no params): prevent empty $0 */
7272 G.global_argv--; /* points to argv[i] of 'script' */
7273 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007274 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007275 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007276 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007277 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007278 goto final_return;
7279 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007280 /* Well, we cannot just declare interactiveness,
7281 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007282 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007283 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007284 case 's':
7285 /* "-s" means "read from stdin", but this is how we always
7286 * operate, so simply do nothing here. */
7287 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007288#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007289 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007290 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007291 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007292 case '$': {
7293 unsigned long long empty_trap_mask;
7294
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007295 G.root_pid = bb_strtou(optarg, &optarg, 16);
7296 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007297 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7298 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007299 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7300 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007301 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007302 optarg++;
7303 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007304 optarg++;
7305 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7306 if (empty_trap_mask != 0) {
7307 int sig;
7308 init_sigmasks();
7309 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7310 for (sig = 1; sig < NSIG; sig++) {
7311 if (empty_trap_mask & (1LL << sig)) {
7312 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7313 sigaddset(&G.blocked_set, sig);
7314 }
7315 }
7316 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7317 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007318# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007319 optarg++;
7320 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007321# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007322 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007323 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007324 case 'R':
7325 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007326 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007327 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007328# if ENABLE_HUSH_FUNCTIONS
7329 case 'F': {
7330 struct function *funcp = new_function(optarg);
7331 /* funcp->name is already set to optarg */
7332 /* funcp->body is set to NULL. It's a special case. */
7333 funcp->body_as_string = argv[optind];
7334 optind++;
7335 break;
7336 }
7337# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007338#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007339 case 'n':
7340 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007341 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007342 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007343 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007344#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007345 fprintf(stderr, "Usage: sh [FILE]...\n"
7346 " or: sh -c command [args]...\n\n");
7347 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007348#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007349 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007350#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007351 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007352 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007353
Denys Vlasenkodea47882009-10-09 15:40:49 +02007354 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007355 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007356 G.root_ppid = getppid();
7357 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007358
7359 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007360 if (argv[0] && argv[0][0] == '-') {
7361 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007362 debug_printf("sourcing /etc/profile\n");
7363 input = fopen_for_read("/etc/profile");
7364 if (input != NULL) {
7365 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007366 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007367 parse_and_run_file(input);
7368 fclose(input);
7369 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007370 /* bash: after sourcing /etc/profile,
7371 * tries to source (in the given order):
7372 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007373 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007374 * bash also sources ~/.bash_logout on exit.
7375 * If called as sh, skips .bash_XXX files.
7376 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007377 }
7378
Denis Vlasenkof9375282009-04-05 19:13:39 +00007379 if (argv[optind]) {
7380 FILE *input;
7381 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007382 * "bash <script>" (which is never interactive (unless -i?))
7383 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007384 * If called as sh, does the same but with $ENV.
7385 */
7386 debug_printf("running script '%s'\n", argv[optind]);
7387 G.global_argv = argv + optind;
7388 G.global_argc = argc - optind;
7389 input = xfopen_for_read(argv[optind]);
7390 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007391 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007392 parse_and_run_file(input);
7393#if ENABLE_FEATURE_CLEAN_UP
7394 fclose(input);
7395#endif
7396 goto final_return;
7397 }
7398
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007399 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007400 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007401 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007402
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007403 /* A shell is interactive if the '-i' flag was given,
7404 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007405 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007406 * no arguments remaining or the -s flag given
7407 * standard input is a terminal
7408 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007409 * Refer to Posix.2, the description of the 'sh' utility.
7410 */
7411#if ENABLE_HUSH_JOB
7412 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007413 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7414 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7415 if (G_saved_tty_pgrp < 0)
7416 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007417
7418 /* try to dup stdin to high fd#, >= 255 */
7419 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7420 if (G_interactive_fd < 0) {
7421 /* try to dup to any fd */
7422 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007423 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007424 /* give up */
7425 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007426 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007427 }
7428 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007429// TODO: track & disallow any attempts of user
7430// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007431 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007432 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007433 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007434 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007435
Mike Frysinger38478a62009-05-20 04:48:06 -04007436 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007437 /* If we were run as 'hush &', sleep until we are
7438 * in the foreground (tty pgrp == our pgrp).
7439 * If we get started under a job aware app (like bash),
7440 * make sure we are now in charge so we don't fight over
7441 * who gets the foreground */
7442 while (1) {
7443 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007444 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7445 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007446 break;
7447 /* send TTIN to ourself (should stop us) */
7448 kill(- shell_pgrp, SIGTTIN);
7449 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007450 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007451
Denis Vlasenkof9375282009-04-05 19:13:39 +00007452 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007453 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007454
Mike Frysinger38478a62009-05-20 04:48:06 -04007455 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007456 /* Set other signals to restore saved_tty_pgrp */
7457 set_fatal_handlers();
7458 /* Put ourselves in our own process group
7459 * (bash, too, does this only if ctty is available) */
7460 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7461 /* Grab control of the terminal */
7462 tcsetpgrp(G_interactive_fd, getpid());
7463 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007464 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007465 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007466 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007467 } else {
7468 init_sigmasks();
7469 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007470#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007471 /* No job control compiled in, only prompt/line editing */
7472 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007473 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7474 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007475 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007476 G_interactive_fd = dup(STDIN_FILENO);
7477 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007478 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007479 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007480 }
7481 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007482 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007483 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007484 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007485 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007486#else
7487 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007488 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007489#endif
7490 /* bash:
7491 * if interactive but not a login shell, sources ~/.bashrc
7492 * (--norc turns this off, --rcfile <file> overrides)
7493 */
7494
7495 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007496 /* note: ash and hush share this string */
7497 printf("\n\n%s %s\n"
7498 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7499 "\n",
7500 bb_banner,
7501 "hush - the humble shell"
7502 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007503 }
7504
Denis Vlasenkof9375282009-04-05 19:13:39 +00007505 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007506
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007507 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007508#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007509 if (G.cwd != bb_msg_unknown)
7510 free((char*)G.cwd);
7511 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007512 while (cur_var) {
7513 struct variable *tmp = cur_var;
7514 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007515 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007516 cur_var = cur_var->next;
7517 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007518 }
Eric Andersen25f27032001-04-26 23:22:31 +00007519#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007520 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007521}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007522
7523
7524#if ENABLE_LASH
7525int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7526int lash_main(int argc, char **argv)
7527{
Denys Vlasenko07934912009-08-20 03:40:04 +02007528 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007529 return hush_main(argc, argv);
7530}
7531#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007532
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007533#if ENABLE_MSH
7534int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7535int msh_main(int argc, char **argv)
7536{
7537 //bb_error_msg("msh is deprecated, please use hush instead");
7538 return hush_main(argc, argv);
7539}
7540#endif
7541
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007542
7543/*
7544 * Built-ins
7545 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007546static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007547{
7548 return 0;
7549}
7550
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007551static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007552{
7553 int argc = 0;
7554 while (*argv) {
7555 argc++;
7556 argv++;
7557 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007558 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007559}
7560
7561static int FAST_FUNC builtin_test(char **argv)
7562{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007563 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007564}
7565
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007566static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007567{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007568 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007569}
7570
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007571#if ENABLE_PRINTF
7572static int FAST_FUNC builtin_printf(char **argv)
7573{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007574 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007575}
7576#endif
7577
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007578static char **skip_dash_dash(char **argv)
7579{
7580 argv++;
7581 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7582 argv++;
7583 return argv;
7584}
7585
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007586static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007587{
7588 int rcode = EXIT_SUCCESS;
7589
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007590 argv = skip_dash_dash(argv);
7591 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007592 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007593 /* bash:
7594 * eval "echo Hi; done" ("done" is syntax error):
7595 * "echo Hi" will not execute too.
7596 */
7597 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007598 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007599 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007600 }
7601 return rcode;
7602}
7603
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007604static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007605{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007606 const char *newdir;
7607
7608 argv = skip_dash_dash(argv);
7609 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007610 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007611 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007612 * bash says "bash: cd: HOME not set" and does nothing
7613 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007614 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007615 const char *home = get_local_var_value("HOME");
7616 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007617 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007618 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007619 /* Mimic bash message exactly */
7620 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007621 return EXIT_FAILURE;
7622 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007623 /* Read current dir (get_cwd(1) is inside) and set PWD.
7624 * Note: do not enforce exporting. If PWD was unset or unexported,
7625 * set it again, but do not export. bash does the same.
7626 */
7627 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007628 return EXIT_SUCCESS;
7629}
7630
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007631static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007632{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007633 argv = skip_dash_dash(argv);
7634 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007635 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007636
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007637 /* Careful: we can end up here after [v]fork. Do not restore
7638 * tty pgrp then, only top-level shell process does that */
7639 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7640 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7641
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007642 /* TODO: if exec fails, bash does NOT exit! We do.
7643 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7644 * and tcsetpgrp, and this is inherently racy.
7645 */
7646 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007647}
7648
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007649static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007650{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007651 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007652
7653 /* interactive bash:
7654 * # trap "echo EEE" EXIT
7655 * # exit
7656 * exit
7657 * There are stopped jobs.
7658 * (if there are _stopped_ jobs, running ones don't count)
7659 * # exit
7660 * exit
7661 # EEE (then bash exits)
7662 *
7663 * we can use G.exiting = -1 as indicator "last cmd was exit"
7664 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007665
7666 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007667 argv = skip_dash_dash(argv);
7668 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007669 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007670 /* mimic bash: exit 123abc == exit 255 + error msg */
7671 xfunc_error_retval = 255;
7672 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007673 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007674}
7675
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007676static void print_escaped(const char *s)
7677{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007678 if (*s == '\'')
7679 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007680 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007681 const char *p = strchrnul(s, '\'');
7682 /* print 'xxxx', possibly just '' */
7683 printf("'%.*s'", (int)(p - s), s);
7684 if (*p == '\0')
7685 break;
7686 s = p;
7687 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007688 /* s points to '; print "'''...'''" */
7689 putchar('"');
7690 do putchar('\''); while (*++s == '\'');
7691 putchar('"');
7692 } while (*s);
7693}
7694
Denys Vlasenko295fef82009-06-03 12:47:26 +02007695#if !ENABLE_HUSH_LOCAL
7696#define helper_export_local(argv, exp, lvl) \
7697 helper_export_local(argv, exp)
7698#endif
7699static void helper_export_local(char **argv, int exp, int lvl)
7700{
7701 do {
7702 char *name = *argv;
7703
7704 /* So far we do not check that name is valid (TODO?) */
7705
7706 if (strchr(name, '=') == NULL) {
7707 struct variable *var;
7708
7709 var = get_local_var(name);
7710 if (exp == -1) { /* unexporting? */
7711 /* export -n NAME (without =VALUE) */
7712 if (var) {
7713 var->flg_export = 0;
7714 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7715 unsetenv(name);
7716 } /* else: export -n NOT_EXISTING_VAR: no-op */
7717 continue;
7718 }
7719 if (exp == 1) { /* exporting? */
7720 /* export NAME (without =VALUE) */
7721 if (var) {
7722 var->flg_export = 1;
7723 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7724 putenv(var->varstr);
7725 continue;
7726 }
7727 }
7728 /* Exporting non-existing variable.
7729 * bash does not put it in environment,
7730 * but remembers that it is exported,
7731 * and does put it in env when it is set later.
7732 * We just set it to "" and export. */
7733 /* Or, it's "local NAME" (without =VALUE).
7734 * bash sets the value to "". */
7735 name = xasprintf("%s=", name);
7736 } else {
7737 /* (Un)exporting/making local NAME=VALUE */
7738 name = xstrdup(name);
7739 }
7740 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7741 } while (*++argv);
7742}
7743
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007744static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007745{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007746 unsigned opt_unexport;
7747
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007748#if ENABLE_HUSH_EXPORT_N
7749 /* "!": do not abort on errors */
7750 opt_unexport = getopt32(argv, "!n");
7751 if (opt_unexport == (uint32_t)-1)
7752 return EXIT_FAILURE;
7753 argv += optind;
7754#else
7755 opt_unexport = 0;
7756 argv++;
7757#endif
7758
7759 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007760 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007761 if (e) {
7762 while (*e) {
7763#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007764 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007765#else
7766 /* ash emits: export VAR='VAL'
7767 * bash: declare -x VAR="VAL"
7768 * we follow ash example */
7769 const char *s = *e++;
7770 const char *p = strchr(s, '=');
7771
7772 if (!p) /* wtf? take next variable */
7773 continue;
7774 /* export var= */
7775 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007776 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007777 putchar('\n');
7778#endif
7779 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007780 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007781 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007782 return EXIT_SUCCESS;
7783 }
7784
Denys Vlasenko295fef82009-06-03 12:47:26 +02007785 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007786
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007787 return EXIT_SUCCESS;
7788}
7789
Denys Vlasenko295fef82009-06-03 12:47:26 +02007790#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007791static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007792{
7793 if (G.func_nest_level == 0) {
7794 bb_error_msg("%s: not in a function", argv[0]);
7795 return EXIT_FAILURE; /* bash compat */
7796 }
7797 helper_export_local(argv, 0, G.func_nest_level);
7798 return EXIT_SUCCESS;
7799}
7800#endif
7801
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007802static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007803{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007804 int sig;
7805 char *new_cmd;
7806
7807 if (!G.traps)
7808 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7809
7810 argv++;
7811 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007812 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007813 /* No args: print all trapped */
7814 for (i = 0; i < NSIG; ++i) {
7815 if (G.traps[i]) {
7816 printf("trap -- ");
7817 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007818 /* note: bash adds "SIG", but only if invoked
7819 * as "bash". If called as "sh", or if set -o posix,
7820 * then it prints short signal names.
7821 * We are printing short names: */
7822 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007823 }
7824 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007825 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007826 return EXIT_SUCCESS;
7827 }
7828
7829 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007830 /* If first arg is a number: reset all specified signals */
7831 sig = bb_strtou(*argv, NULL, 10);
7832 if (errno == 0) {
7833 int ret;
7834 process_sig_list:
7835 ret = EXIT_SUCCESS;
7836 while (*argv) {
7837 sig = get_signum(*argv++);
7838 if (sig < 0 || sig >= NSIG) {
7839 ret = EXIT_FAILURE;
7840 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007841 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007842 continue;
7843 }
7844
7845 free(G.traps[sig]);
7846 G.traps[sig] = xstrdup(new_cmd);
7847
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007848 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007849 get_signame(sig), sig, G.traps[sig]);
7850
7851 /* There is no signal for 0 (EXIT) */
7852 if (sig == 0)
7853 continue;
7854
7855 if (new_cmd) {
7856 sigaddset(&G.blocked_set, sig);
7857 } else {
7858 /* There was a trap handler, we are removing it
7859 * (if sig has non-DFL handling,
7860 * we don't need to do anything) */
7861 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7862 continue;
7863 sigdelset(&G.blocked_set, sig);
7864 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007865 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007866 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007867 return ret;
7868 }
7869
7870 if (!argv[1]) { /* no second arg */
7871 bb_error_msg("trap: invalid arguments");
7872 return EXIT_FAILURE;
7873 }
7874
7875 /* First arg is "-": reset all specified to default */
7876 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7877 /* Everything else: set arg as signal handler
7878 * (includes "" case, which ignores signal) */
7879 if (argv[0][0] == '-') {
7880 if (argv[0][1] == '\0') { /* "-" */
7881 /* new_cmd remains NULL: "reset these sigs" */
7882 goto reset_traps;
7883 }
7884 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7885 argv++;
7886 }
7887 /* else: "-something", no special meaning */
7888 }
7889 new_cmd = *argv;
7890 reset_traps:
7891 argv++;
7892 goto process_sig_list;
7893}
7894
Mike Frysinger93cadc22009-05-27 17:06:25 -04007895/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007896static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007897{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007898 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007899
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007900 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007901 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007902 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007903
7904 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007905 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007906 type = "an alias";*/
7907#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007908 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007909 type = "a function";
7910#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007911 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007912 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007913 else if ((path = find_in_path(*argv)) != NULL)
7914 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007915 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007916 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007917 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007918 continue;
7919 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007920
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007921 printf("%s is %s\n", *argv, type);
7922 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007923 }
7924
7925 return ret;
7926}
7927
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007928#if ENABLE_HUSH_JOB
7929/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007930static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007931{
7932 int i, jobnum;
7933 struct pipe *pi;
7934
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007935 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007936 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007937
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007938 /* If they gave us no args, assume they want the last backgrounded task */
7939 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007940 for (pi = G.job_list; pi; pi = pi->next) {
7941 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007942 goto found;
7943 }
7944 }
7945 bb_error_msg("%s: no current job", argv[0]);
7946 return EXIT_FAILURE;
7947 }
7948 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7949 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7950 return EXIT_FAILURE;
7951 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007952 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007953 if (pi->jobid == jobnum) {
7954 goto found;
7955 }
7956 }
7957 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7958 return EXIT_FAILURE;
7959 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007960 /* TODO: bash prints a string representation
7961 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007962 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007963 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007964 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007965 }
7966
7967 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007968 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7969 for (i = 0; i < pi->num_cmds; i++) {
7970 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7971 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007972 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007973 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007974
7975 i = kill(- pi->pgrp, SIGCONT);
7976 if (i < 0) {
7977 if (errno == ESRCH) {
7978 delete_finished_bg_job(pi);
7979 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007980 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007981 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007982 }
7983
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007984 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007985 remove_bg_job(pi);
7986 return checkjobs_and_fg_shell(pi);
7987 }
7988 return EXIT_SUCCESS;
7989}
7990#endif
7991
7992#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007993static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007994{
7995 const struct built_in_command *x;
7996
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007997 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007998 "Built-in commands:\n"
7999 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008000 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008001 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008002 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008003 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008004 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008005 return EXIT_SUCCESS;
8006}
8007#endif
8008
8009#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008010static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008011{
8012 struct pipe *job;
8013 const char *status_string;
8014
Denis Vlasenko87a86552008-07-29 19:43:10 +00008015 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008016 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008017 status_string = "Stopped";
8018 else
8019 status_string = "Running";
8020
8021 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8022 }
8023 return EXIT_SUCCESS;
8024}
8025#endif
8026
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008027#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008028static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008029{
8030 void *p;
8031 unsigned long l;
8032
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008033# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008034 /* Optional. Reduces probability of false positives */
8035 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008036# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008037 /* Crude attempt to find where "free memory" starts,
8038 * sans fragmentation. */
8039 p = malloc(240);
8040 l = (unsigned long)p;
8041 free(p);
8042 p = malloc(3400);
8043 if (l < (unsigned long)p) l = (unsigned long)p;
8044 free(p);
8045
8046 if (!G.memleak_value)
8047 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008048
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008049 l -= G.memleak_value;
8050 if ((long)l < 0)
8051 l = 0;
8052 l /= 1024;
8053 if (l > 127)
8054 l = 127;
8055
8056 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8057 return l;
8058}
8059#endif
8060
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008061static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008062{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008063 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008064 return EXIT_SUCCESS;
8065}
8066
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008067static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008068{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008069 const char *r;
8070 char *opt_n = NULL;
8071 char *opt_p = NULL;
8072 char *opt_t = NULL;
8073 char *opt_u = NULL;
8074 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008075
Denys Vlasenko03dad222010-01-12 23:29:57 +01008076 /* "!": do not abort on errors.
8077 * Option string must start with "sr" to match BUILTIN_READ_xxx
8078 */
8079 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8080 if (read_flags == (uint32_t)-1)
8081 return EXIT_FAILURE;
8082 argv += optind;
8083
8084 r = shell_builtin_read(set_local_var_from_halves,
8085 argv,
8086 get_local_var_value("IFS"), /* can be NULL */
8087 read_flags,
8088 opt_n,
8089 opt_p,
8090 opt_t,
8091 opt_u
8092 );
8093
8094 if ((uintptr_t)r > 1) {
8095 bb_error_msg("%s", r);
8096 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008097 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008098
Denys Vlasenko03dad222010-01-12 23:29:57 +01008099 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008100}
8101
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008102/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8103 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008104 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008105 * set [-abCefhmnuvx] [-o option] [argument...]
8106 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008107 * set -- [argument...]
8108 * set -o
8109 * set +o
8110 * Implementations shall support the options in both their hyphen and
8111 * plus-sign forms. These options can also be specified as options to sh.
8112 * Examples:
8113 * Write out all variables and their values: set
8114 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8115 * Turn on the -x and -v options: set -xv
8116 * Unset all positional parameters: set --
8117 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8118 * Set the positional parameters to the expansion of x, even if x expands
8119 * with a leading '-' or '+': set -- $x
8120 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008121 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008122 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008123static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008124{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008125 int n;
8126 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008127 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008128
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008129 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008130 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008131 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008132 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008133 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008134 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008135
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008136 do {
8137 if (!strcmp(arg, "--")) {
8138 ++argv;
8139 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008140 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008141 if (arg[0] != '+' && arg[0] != '-')
8142 break;
8143 for (n = 1; arg[n]; ++n)
8144 if (set_mode(arg[0], arg[n]))
8145 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008146 } while ((arg = *++argv) != NULL);
8147 /* Now argv[0] is 1st argument */
8148
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008149 if (arg == NULL)
8150 return EXIT_SUCCESS;
8151 set_argv:
8152
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008153 /* NB: G.global_argv[0] ($0) is never freed/changed */
8154 g_argv = G.global_argv;
8155 if (G.global_args_malloced) {
8156 pp = g_argv;
8157 while (*++pp)
8158 free(*pp);
8159 g_argv[1] = NULL;
8160 } else {
8161 G.global_args_malloced = 1;
8162 pp = xzalloc(sizeof(pp[0]) * 2);
8163 pp[0] = g_argv[0]; /* retain $0 */
8164 g_argv = pp;
8165 }
8166 /* This realloc's G.global_argv */
8167 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8168
8169 n = 1;
8170 while (*++pp)
8171 n++;
8172 G.global_argc = n;
8173
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008174 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008175
8176 /* Nothing known, so abort */
8177 error:
8178 bb_error_msg("set: %s: invalid option", arg);
8179 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008180}
8181
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008182static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008183{
8184 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008185 argv = skip_dash_dash(argv);
8186 if (argv[0]) {
8187 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008188 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008189 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008190 if (G.global_args_malloced) {
8191 int m = 1;
8192 while (m <= n)
8193 free(G.global_argv[m++]);
8194 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008195 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008196 memmove(&G.global_argv[1], &G.global_argv[n+1],
8197 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008198 return EXIT_SUCCESS;
8199 }
8200 return EXIT_FAILURE;
8201}
8202
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008203static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008204{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008205 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008206 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008207 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008208#if ENABLE_HUSH_FUNCTIONS
8209 smallint sv_flg;
8210#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008211
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008212 argv = skip_dash_dash(argv);
8213 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008214 if (!filename) {
8215 /* bash says: "bash: .: filename argument required" */
8216 return 2; /* bash compat */
8217 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008218 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008219 if (!strchr(filename, '/')) {
8220 arg_path = find_in_path(filename);
8221 if (arg_path)
8222 filename = arg_path;
8223 }
8224 input = fopen_or_warn(filename, "r");
8225 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008226 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008227 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008228 return EXIT_FAILURE;
8229 }
8230 close_on_exec_on(fileno(input));
8231
Mike Frysinger885b6f22009-04-18 21:04:25 +00008232#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008233 sv_flg = G.flag_return_in_progress;
8234 /* "we are inside sourced file, ok to use return" */
8235 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008236#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008237 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008238
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008239 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008240 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008241
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008242 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008243#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008244 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008245#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008246
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008247 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008248}
8249
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008250static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008251{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008252 int rc;
8253 mode_t mask;
8254
8255 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008256 argv = skip_dash_dash(argv);
8257 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008258 mode_t old_mask = mask;
8259
8260 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008261 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008262 mask ^= 0777;
8263 if (rc == 0) {
8264 mask = old_mask;
8265 /* bash messages:
8266 * bash: umask: 'q': invalid symbolic mode operator
8267 * bash: umask: 999: octal number out of range
8268 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008269 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008270 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008271 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008272 rc = 1;
8273 /* Mimic bash */
8274 printf("%04o\n", (unsigned) mask);
8275 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008276 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008277 umask(mask);
8278
8279 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008280}
8281
Mike Frysingerd690f682009-03-30 06:50:54 +00008282/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008283static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008284{
Mike Frysingerd690f682009-03-30 06:50:54 +00008285 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008286 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008287
Denis Vlasenko28e67962009-04-26 23:22:40 +00008288 /* "!": do not abort on errors */
8289 /* "+": stop at 1st non-option */
8290 opts = getopt32(argv, "!+vf");
8291 if (opts == (unsigned)-1)
8292 return EXIT_FAILURE;
8293 if (opts == 3) {
8294 bb_error_msg("unset: -v and -f are exclusive");
8295 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008296 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008297 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008298
8299 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008300 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008301 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008302 if (unset_local_var(*argv)) {
8303 /* unset <nonexistent_var> doesn't fail.
8304 * Error is when one tries to unset RO var.
8305 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008306 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008307 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008308 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008309#if ENABLE_HUSH_FUNCTIONS
8310 else {
8311 unset_func(*argv);
8312 }
8313#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008314 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008315 }
8316 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008317}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008318
Mike Frysinger56bdea12009-03-28 20:01:58 +00008319/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008320static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008321{
8322 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008323 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008324
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008325 argv = skip_dash_dash(argv);
8326 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008327 /* Don't care about wait results */
8328 /* Note 1: must wait until there are no more children */
8329 /* Note 2: must be interruptible */
8330 /* Examples:
8331 * $ sleep 3 & sleep 6 & wait
8332 * [1] 30934 sleep 3
8333 * [2] 30935 sleep 6
8334 * [1] Done sleep 3
8335 * [2] Done sleep 6
8336 * $ sleep 3 & sleep 6 & wait
8337 * [1] 30936 sleep 3
8338 * [2] 30937 sleep 6
8339 * [1] Done sleep 3
8340 * ^C <-- after ~4 sec from keyboard
8341 * $
8342 */
8343 sigaddset(&G.blocked_set, SIGCHLD);
8344 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8345 while (1) {
8346 checkjobs(NULL);
8347 if (errno == ECHILD)
8348 break;
8349 /* Wait for SIGCHLD or any other signal of interest */
8350 /* sigtimedwait with infinite timeout: */
8351 sig = sigwaitinfo(&G.blocked_set, NULL);
8352 if (sig > 0) {
8353 sig = check_and_run_traps(sig);
8354 if (sig && sig != SIGCHLD) { /* see note 2 */
8355 ret = 128 + sig;
8356 break;
8357 }
8358 }
8359 }
8360 sigdelset(&G.blocked_set, SIGCHLD);
8361 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8362 return ret;
8363 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008364
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008365 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008366 while (*argv) {
8367 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008368 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008369 /* mimic bash message */
8370 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008371 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008372 }
8373 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008374 if (WIFSIGNALED(status))
8375 ret = 128 + WTERMSIG(status);
8376 else if (WIFEXITED(status))
8377 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008378 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008379 ret = EXIT_FAILURE;
8380 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008381 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008382 ret = 127;
8383 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008384 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008385 }
8386
8387 return ret;
8388}
8389
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008390#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8391static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8392{
8393 if (argv[1]) {
8394 def = bb_strtou(argv[1], NULL, 10);
8395 if (errno || def < def_min || argv[2]) {
8396 bb_error_msg("%s: bad arguments", argv[0]);
8397 def = UINT_MAX;
8398 }
8399 }
8400 return def;
8401}
8402#endif
8403
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008404#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008405static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008406{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008407 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008408 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008409 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008410 return EXIT_SUCCESS; /* bash compat */
8411 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008412 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008413
8414 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8415 if (depth == UINT_MAX)
8416 G.flag_break_continue = BC_BREAK;
8417 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008418 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008419
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008420 return EXIT_SUCCESS;
8421}
8422
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008423static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008424{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008425 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8426 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008427}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008428#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008429
8430#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008431static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008432{
8433 int rc;
8434
8435 if (G.flag_return_in_progress != -1) {
8436 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8437 return EXIT_FAILURE; /* bash compat */
8438 }
8439
8440 G.flag_return_in_progress = 1;
8441
8442 /* bash:
8443 * out of range: wraps around at 256, does not error out
8444 * non-numeric param:
8445 * f() { false; return qwe; }; f; echo $?
8446 * bash: return: qwe: numeric argument required <== we do this
8447 * 255 <== we also do this
8448 */
8449 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8450 return rc;
8451}
8452#endif