blob: 339f3349a5f69b1ca098580dbbbc44a3c3e35e88 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
45 * tilde expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Denys Vlasenko349ef962010-05-21 15:46:24 +020047 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020050 * make complex ${var%...} constructs support optional
51 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000052 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020053 * Bash compat TODO:
54 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020055 * reserved words: function select
56 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020057 * process substitution: <(list) and >(list)
58 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020059 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020060 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020063 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020064 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020066 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenkobbecd742010-10-03 17:22:52 +020067 *
68 * Won't do:
69 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020070 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
72 * compare with:
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020076 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020077 * Note2: bash 3.2.33(1) does this only if export word itself
78 * is not quoted:
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
80 * aaa bbb
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
82 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000083 */
Denys Vlasenko8da415e2010-12-05 01:30:14 +010084#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
86 )
87# include <malloc.h> /* for malloc_trim */
88#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +000089#include <glob.h>
90/* #include <dmalloc.h> */
91#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000092# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000093#endif
Denys Vlasenko03dad222010-01-12 23:29:57 +010094
Denys Vlasenko20704f02011-03-23 17:59:27 +010095#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
96#include "unicode.h"
Denys Vlasenko03dad222010-01-12 23:29:57 +010097#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000098#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000099#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +0200100#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200101# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +0200102#else
103# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200104#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000105#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200106# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000107#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000108
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200109//config:config HUSH
110//config: bool "hush"
111//config: default y
112//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200113//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200114//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
115//config: case/esac. Redirections, here documents, $((arithmetic))
116//config: and functions are supported.
117//config:
118//config: It will compile and work on no-mmu systems.
119//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +0200120//config: It does not handle select, aliases, tilde expansion,
121//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200122//config:
123//config:config HUSH_BASH_COMPAT
124//config: bool "bash-compatible extensions"
125//config: default y
126//config: depends on HUSH
127//config: help
128//config: Enable bash-compatible extensions.
129//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200130//config:config HUSH_BRACE_EXPANSION
131//config: bool "Brace expansion"
132//config: default y
133//config: depends on HUSH_BASH_COMPAT
134//config: help
135//config: Enable {abc,def} extension.
136//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config:config HUSH_HELP
138//config: bool "help builtin"
139//config: default y
140//config: depends on HUSH
141//config: help
142//config: Enable help builtin in hush. Code size + ~1 kbyte.
143//config:
144//config:config HUSH_INTERACTIVE
145//config: bool "Interactive mode"
146//config: default y
147//config: depends on HUSH
148//config: help
149//config: Enable interactive mode (prompt and command editing).
150//config: Without this, hush simply reads and executes commands
151//config: from stdin just like a shell script from a file.
152//config: No prompt, no PS1/PS2 magic shell variables.
153//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200154//config:config HUSH_SAVEHISTORY
155//config: bool "Save command history to .hush_history"
156//config: default y
157//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
158//config: help
159//config: Enable history saving in hush.
160//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config:config HUSH_JOB
162//config: bool "Job control"
163//config: default y
164//config: depends on HUSH_INTERACTIVE
165//config: help
166//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
167//config: command (not entire shell), fg/bg builtins work. Without this option,
168//config: "cmd &" still works by simply spawning a process and immediately
169//config: prompting for next command (or executing next command in a script),
170//config: but no separate process group is formed.
171//config:
172//config:config HUSH_TICK
173//config: bool "Process substitution"
174//config: default y
175//config: depends on HUSH
176//config: help
177//config: Enable process substitution `command` and $(command) in hush.
178//config:
179//config:config HUSH_IF
180//config: bool "Support if/then/elif/else/fi"
181//config: default y
182//config: depends on HUSH
183//config: help
184//config: Enable if/then/elif/else/fi in hush.
185//config:
186//config:config HUSH_LOOPS
187//config: bool "Support for, while and until loops"
188//config: default y
189//config: depends on HUSH
190//config: help
191//config: Enable for, while and until loops in hush.
192//config:
193//config:config HUSH_CASE
194//config: bool "Support case ... esac statement"
195//config: default y
196//config: depends on HUSH
197//config: help
198//config: Enable case ... esac statement in hush. +400 bytes.
199//config:
200//config:config HUSH_FUNCTIONS
201//config: bool "Support funcname() { commands; } syntax"
202//config: default y
203//config: depends on HUSH
204//config: help
205//config: Enable support for shell functions in hush. +800 bytes.
206//config:
207//config:config HUSH_LOCAL
208//config: bool "Support local builtin"
209//config: default y
210//config: depends on HUSH_FUNCTIONS
211//config: help
212//config: Enable support for local variables in functions.
213//config:
214//config:config HUSH_RANDOM_SUPPORT
215//config: bool "Pseudorandom generator and $RANDOM variable"
216//config: default y
217//config: depends on HUSH
218//config: help
219//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
220//config: Each read of "$RANDOM" will generate a new pseudorandom value.
221//config:
222//config:config HUSH_EXPORT_N
223//config: bool "Support 'export -n' option"
224//config: default y
225//config: depends on HUSH
226//config: help
227//config: export -n unexports variables. It is a bash extension.
228//config:
229//config:config HUSH_MODE_X
230//config: bool "Support 'hush -x' option and 'set -x' command"
231//config: default y
232//config: depends on HUSH
233//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200234//config: This instructs hush to print commands before execution.
235//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200236//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200237//config:config MSH
238//config: bool "msh (deprecated: aliased to hush)"
239//config: default n
240//config: select HUSH
241//config: help
242//config: msh is deprecated and will be removed, please migrate to hush.
243//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200244
Denys Vlasenko20704f02011-03-23 17:59:27 +0100245//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
246//applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
247//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
248//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
249
250//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
251//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
252
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100253/* -i (interactive) and -s (read stdin) are also accepted,
254 * but currently do nothing, therefore aren't shown in help.
255 * NOMMU-specific options are not meant to be used by users,
256 * therefore we don't show them either.
257 */
258//usage:#define hush_trivial_usage
Denys Vlasenko6b6af532011-03-08 10:24:17 +0100259//usage: "[-nx] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100260//usage:#define hush_full_usage "\n\n"
261//usage: "Unix shell interpreter"
262
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100263//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100264//usage:#define msh_full_usage hush_full_usage
265
266//usage:#if ENABLE_FEATURE_SH_IS_HUSH
267//usage:# define sh_trivial_usage hush_trivial_usage
268//usage:# define sh_full_usage hush_full_usage
269//usage:#endif
270//usage:#if ENABLE_FEATURE_BASH_IS_HUSH
271//usage:# define bash_trivial_usage hush_trivial_usage
272//usage:# define bash_full_usage hush_full_usage
273//usage:#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200274
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000275
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200276/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000277#define LEAK_HUNTING 0
278#define BUILD_AS_NOMMU 0
279/* Enable/disable sanity checks. Ok to enable in production,
280 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
281 * Keeping 1 for now even in released versions.
282 */
283#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200284/* Slightly bigger (+200 bytes), but faster hush.
285 * So far it only enables a trick with counting SIGCHLDs and forks,
286 * which allows us to do fewer waitpid's.
287 * (we can detect a case where neither forks were done nor SIGCHLDs happened
288 * and therefore waitpid will return the same result as last time)
289 */
290#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200291/* TODO: implement simplified code for users which do not need ${var%...} ops
292 * So far ${var%...} ops are always enabled:
293 */
294#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000295
296
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000297#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000298# undef BB_MMU
299# undef USE_FOR_NOMMU
300# undef USE_FOR_MMU
301# define BB_MMU 0
302# define USE_FOR_NOMMU(...) __VA_ARGS__
303# define USE_FOR_MMU(...)
304#endif
305
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200306#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100307#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000308/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000309# undef CONFIG_FEATURE_SH_STANDALONE
310# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000311# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100312# undef IF_NOT_FEATURE_SH_STANDALONE
313# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000314# define IF_FEATURE_SH_STANDALONE(...)
315# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000316#endif
317
Denis Vlasenko05743d72008-02-10 12:10:08 +0000318#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000319# undef ENABLE_FEATURE_EDITING
320# define ENABLE_FEATURE_EDITING 0
321# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
322# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000323#endif
324
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000325/* Do we support ANY keywords? */
326#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000327# define HAS_KEYWORDS 1
328# define IF_HAS_KEYWORDS(...) __VA_ARGS__
329# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000330#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000331# define HAS_KEYWORDS 0
332# define IF_HAS_KEYWORDS(...)
333# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000334#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000335
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000336/* If you comment out one of these below, it will be #defined later
337 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000338#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000339/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000340#define debug_printf_parse(...) do {} while (0)
341#define debug_print_tree(a, b) do {} while (0)
342#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000343#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000344#define debug_printf_jobs(...) do {} while (0)
345#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200346#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000347#define debug_printf_glob(...) do {} while (0)
348#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000349#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000350#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000351
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000352#define ERR_PTR ((void*)(long)1)
353
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200354#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000355
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200356#define _SPECIAL_VARS_STR "_*@$!?#"
357#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
358#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200359#if ENABLE_HUSH_BASH_COMPAT
360/* Support / and // replace ops */
361/* Note that // is stored as \ in "encoded" string representation */
362# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
363# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
364# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
365#else
366# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
367# define VAR_SUBST_OPS "%#:-=+?"
368# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
369#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200370
371#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000372
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200373struct variable;
374
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000375static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
376
377/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000378 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000379 */
380#if !BB_MMU
381typedef struct nommu_save_t {
382 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200383 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000384 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000385 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000386} nommu_save_t;
387#endif
388
Denys Vlasenko9b782552010-09-08 13:33:26 +0200389enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000390 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000391#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000392 RES_IF ,
393 RES_THEN ,
394 RES_ELIF ,
395 RES_ELSE ,
396 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000397#endif
398#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000399 RES_FOR ,
400 RES_WHILE ,
401 RES_UNTIL ,
402 RES_DO ,
403 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000404#endif
405#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000406 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000407#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000408#if ENABLE_HUSH_CASE
409 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200410 /* three pseudo-keywords support contrived "case" syntax: */
411 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
412 RES_MATCH , /* "word)" */
413 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000414 RES_ESAC ,
415#endif
416 RES_XXXX ,
417 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200418};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000419
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000420typedef struct o_string {
421 char *data;
422 int length; /* position where data is appended */
423 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200424 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000425 /* At least some part of the string was inside '' or "",
426 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200427 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000428 smallint has_empty_slot;
429 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
430} o_string;
431enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200432 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
433 EXP_FLAG_GLOB = 0x2,
434 /* Protect newly added chars against globbing
435 * by prepending \ to *, ?, [, \ */
436 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
437};
438enum {
439 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000440 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200441 NOT_ASSIGNMENT = 2,
442 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
443 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000444};
445/* Used for initialization: o_string foo = NULL_O_STRING; */
446#define NULL_O_STRING { NULL }
447
448/* I can almost use ordinary FILE*. Is open_memstream() universally
449 * available? Where is it documented? */
450typedef struct in_str {
451 const char *p;
452 /* eof_flag=1: last char in ->p is really an EOF */
453 char eof_flag; /* meaningless if ->p == NULL */
454 char peek_buf[2];
455#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000456 smallint promptmode; /* 0: PS1, 1: PS2 */
457#endif
458 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200459 int (*get) (struct in_str *) FAST_FUNC;
460 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000461} in_str;
462#define i_getch(input) ((input)->get(input))
463#define i_peek(input) ((input)->peek(input))
464
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200465/* The descrip member of this structure is only used to make
466 * debugging output pretty */
467static const struct {
468 int mode;
469 signed char default_fd;
470 char descrip[3];
471} redir_table[] = {
472 { O_RDONLY, 0, "<" },
473 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
474 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
475 { O_CREAT|O_RDWR, 1, "<>" },
476 { O_RDONLY, 0, "<<" },
477/* Should not be needed. Bogus default_fd helps in debugging */
478/* { O_RDONLY, 77, "<<" }, */
479};
480
Eric Andersen25f27032001-04-26 23:22:31 +0000481struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000482 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000483 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000484 int rd_fd; /* fd to redirect */
485 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
486 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000487 smallint rd_type; /* (enum redir_type) */
488 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000489 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200490 * bit 0: do we need to trim leading tabs?
491 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000492 */
Eric Andersen25f27032001-04-26 23:22:31 +0000493};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000494typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200495 REDIRECT_INPUT = 0,
496 REDIRECT_OVERWRITE = 1,
497 REDIRECT_APPEND = 2,
498 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000499 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200500 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000501
502 REDIRFD_CLOSE = -3,
503 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000504 REDIRFD_TO_FILE = -1,
505 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000506
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000507 HEREDOC_SKIPTABS = 1,
508 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000509} redir_type;
510
Eric Andersen25f27032001-04-26 23:22:31 +0000511
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000512struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000513 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000514 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000515 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200516 smallint cmd_type; /* CMD_xxx */
517#define CMD_NORMAL 0
518#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200519#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200520/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200521# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000522#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200523#if ENABLE_HUSH_FUNCTIONS
524# define CMD_FUNCDEF 3
525#endif
526
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100527 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200528 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
529 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000530#if !BB_MMU
531 char *group_as_string;
532#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000533#if ENABLE_HUSH_FUNCTIONS
534 struct function *child_func;
535/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200536 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000537 * When we execute "f1() {a;}" cmd, we create new function and clear
538 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200539 * When we execute "f1() {b;}", we notice that f1 exists,
540 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000541 * we put those fields back into cmd->xxx
542 * (struct function has ->parent_cmd ptr to facilitate that).
543 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
544 * Without this trick, loop would execute a;b;b;b;...
545 * instead of correct sequence a;b;a;b;...
546 * When command is freed, it severs the link
547 * (sets ->child_func->parent_cmd to NULL).
548 */
549#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000550 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000551/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
552 * and on execution these are substituted with their values.
553 * Substitution can make _several_ words out of one argv[n]!
554 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000555 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000556 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000557 struct redir_struct *redirects; /* I/O redirections */
558};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000559/* Is there anything in this command at all? */
560#define IS_NULL_CMD(cmd) \
561 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
562
Eric Andersen25f27032001-04-26 23:22:31 +0000563struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000564 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000565 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000566 int alive_cmds; /* number of commands running (not exited) */
567 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000568#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000569 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000570 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000571 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000572#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000573 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000574 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000575 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
576 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000577};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000578typedef enum pipe_style {
579 PIPE_SEQ = 1,
580 PIPE_AND = 2,
581 PIPE_OR = 3,
582 PIPE_BG = 4,
583} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000584/* Is there anything in this pipe at all? */
585#define IS_NULL_PIPE(pi) \
586 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000587
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000588/* This holds pointers to the various results of parsing */
589struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000590 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000591 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000592 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000593 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000594 /* last command in pipe (being constructed right now) */
595 struct command *command;
596 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000597 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000598#if !BB_MMU
599 o_string as_string;
600#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000601#if HAS_KEYWORDS
602 smallint ctx_res_w;
603 smallint ctx_inverted; /* "! cmd | cmd" */
604#if ENABLE_HUSH_CASE
605 smallint ctx_dsemicolon; /* ";;" seen */
606#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000607 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
608 int old_flag;
609 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000610 * example: "if pipe1; pipe2; then pipe3; fi"
611 * when we see "if" or "then", we malloc and copy current context,
612 * and make ->stack point to it. then we parse pipeN.
613 * when closing "then" / fi" / whatever is found,
614 * we move list_head into ->stack->command->group,
615 * copy ->stack into current context, and delete ->stack.
616 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000617 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000618 struct parse_context *stack;
619#endif
620};
621
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000622/* On program start, environ points to initial environment.
623 * putenv adds new pointers into it, unsetenv removes them.
624 * Neither of these (de)allocates the strings.
625 * setenv allocates new strings in malloc space and does putenv,
626 * and thus setenv is unusable (leaky) for shell's purposes */
627#define setenv(...) setenv_is_leaky_dont_use()
628struct variable {
629 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000630 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200631#if ENABLE_HUSH_LOCAL
632 unsigned func_nest_level;
633#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000634 int max_len; /* if > 0, name is part of initial env; else name is malloced */
635 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000636 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000637};
638
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000639enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000640 BC_BREAK = 1,
641 BC_CONTINUE = 2,
642};
643
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000644#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000645struct function {
646 struct function *next;
647 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000648 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000649 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200650# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000651 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200652# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000653};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000654#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000655
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000656
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100657/* set -/+o OPT support. (TODO: make it optional)
658 * bash supports the following opts:
659 * allexport off
660 * braceexpand on
661 * emacs on
662 * errexit off
663 * errtrace off
664 * functrace off
665 * hashall on
666 * histexpand off
667 * history on
668 * ignoreeof off
669 * interactive-comments on
670 * keyword off
671 * monitor on
672 * noclobber off
673 * noexec off
674 * noglob off
675 * nolog off
676 * notify off
677 * nounset off
678 * onecmd off
679 * physical off
680 * pipefail off
681 * posix off
682 * privileged off
683 * verbose off
684 * vi off
685 * xtrace off
686 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800687static const char o_opt_strings[] ALIGN1 =
688 "pipefail\0"
689 "noexec\0"
690#if ENABLE_HUSH_MODE_X
691 "xtrace\0"
692#endif
693 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100694enum {
695 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800696 OPT_O_NOEXEC,
697#if ENABLE_HUSH_MODE_X
698 OPT_O_XTRACE,
699#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100700 NUM_OPT_O
701};
702
703
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000704/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000705/* Sorted roughly by size (smaller offsets == smaller code) */
706struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000707 /* interactive_fd != 0 means we are an interactive shell.
708 * If we are, then saved_tty_pgrp can also be != 0, meaning
709 * that controlling tty is available. With saved_tty_pgrp == 0,
710 * job control still works, but terminal signals
711 * (^C, ^Z, ^Y, ^\) won't work at all, and background
712 * process groups can only be created with "cmd &".
713 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
714 * to give tty to the foreground process group,
715 * and will take it back when the group is stopped (^Z)
716 * or killed (^C).
717 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000718#if ENABLE_HUSH_INTERACTIVE
719 /* 'interactive_fd' is a fd# open to ctty, if we have one
720 * _AND_ if we decided to act interactively */
721 int interactive_fd;
722 const char *PS1;
723 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000724# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000725#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000726# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000727#endif
728#if ENABLE_FEATURE_EDITING
729 line_input_t *line_input_state;
730#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000731 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200732 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000733 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200734#if ENABLE_HUSH_RANDOM_SUPPORT
735 random_t random_gen;
736#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000737#if ENABLE_HUSH_JOB
738 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000739 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000740 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000741 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400742# define G_saved_tty_pgrp (G.saved_tty_pgrp)
743#else
744# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000745#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100746 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100747#if ENABLE_HUSH_MODE_X
748# define G_x_mode (G.o_opt[OPT_O_XTRACE])
749#else
750# define G_x_mode 0
751#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000752 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000753#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000754 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000755#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000756#if ENABLE_HUSH_FUNCTIONS
757 /* 0: outside of a function (or sourced file)
758 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000759 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000760 */
761 smallint flag_return_in_progress;
762#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000763 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000764 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000765 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000766 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000767 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100768 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000769 /* how many non-NULL argv's we have. NB: $# + 1 */
770 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000771 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000772#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000773 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000774#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000775#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000776 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000777 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000778#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000779 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000780 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200781 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200782 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000783#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000784 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200785# if ENABLE_HUSH_LOCAL
786 struct variable **shadowed_vars_pp;
787 unsigned func_nest_level;
788# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000789#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000790 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200791#if ENABLE_HUSH_FAST
792 unsigned count_SIGCHLD;
793 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200794 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200795#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000796 /* which signals have non-DFL handler (even with no traps set)? */
797 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000798 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000799 sigset_t blocked_set;
800 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000801#if HUSH_DEBUG
802 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000803 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000804#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200805 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000806};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000807#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000808/* Not #defining name to G.name - this quickly gets unwieldy
809 * (too many defines). Also, I actually prefer to see when a variable
810 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000811#define INIT_G() do { \
812 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
813} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000814
815
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000816/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200817static int builtin_cd(char **argv) FAST_FUNC;
818static int builtin_echo(char **argv) FAST_FUNC;
819static int builtin_eval(char **argv) FAST_FUNC;
820static int builtin_exec(char **argv) FAST_FUNC;
821static int builtin_exit(char **argv) FAST_FUNC;
822static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000823#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200824static int builtin_fg_bg(char **argv) FAST_FUNC;
825static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000826#endif
827#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200828static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000829#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200830#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200831static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200832#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000833#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200834static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000835#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400836#if ENABLE_PRINTF
837static int builtin_printf(char **argv) FAST_FUNC;
838#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200839static int builtin_pwd(char **argv) FAST_FUNC;
840static int builtin_read(char **argv) FAST_FUNC;
841static int builtin_set(char **argv) FAST_FUNC;
842static int builtin_shift(char **argv) FAST_FUNC;
843static int builtin_source(char **argv) FAST_FUNC;
844static int builtin_test(char **argv) FAST_FUNC;
845static int builtin_trap(char **argv) FAST_FUNC;
846static int builtin_type(char **argv) FAST_FUNC;
847static int builtin_true(char **argv) FAST_FUNC;
848static int builtin_umask(char **argv) FAST_FUNC;
849static int builtin_unset(char **argv) FAST_FUNC;
850static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000851#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200852static int builtin_break(char **argv) FAST_FUNC;
853static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000854#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000855#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200856static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000857#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000858
859/* Table of built-in functions. They can be forked or not, depending on
860 * context: within pipes, they fork. As simple commands, they do not.
861 * When used in non-forking context, they can change global variables
862 * in the parent shell process. If forked, of course they cannot.
863 * For example, 'unset foo | whatever' will parse and run, but foo will
864 * still be set at the end. */
865struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100866 const char *b_cmd;
867 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000868#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100869 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200870# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000871#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200872# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000873#endif
874};
875
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200876static const struct built_in_command bltins1[] = {
877 BLTIN("." , builtin_source , "Run commands in a file"),
878 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000879#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200880 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000881#endif
882#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200883 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000884#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200885 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000886#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200887 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000888#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200889 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
890 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
891 BLTIN("exit" , builtin_exit , "Exit"),
892 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000893#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200894 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000895#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000896#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200897 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000898#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000899#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200900 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000901#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200902#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200903 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200904#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000905#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200906 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000907#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200908 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000909#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200910 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000911#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200912 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
913 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200914#if ENABLE_HUSH_BASH_COMPAT
915 BLTIN("source" , builtin_source , "Run commands in a file"),
916#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200917 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100918 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100919 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200920 BLTIN("umask" , builtin_umask , "Set file creation mask"),
921 BLTIN("unset" , builtin_unset , "Unset variables"),
922 BLTIN("wait" , builtin_wait , "Wait for process"),
923};
924/* For now, echo and test are unconditionally enabled.
925 * Maybe make it configurable? */
926static const struct built_in_command bltins2[] = {
927 BLTIN("[" , builtin_test , NULL),
928 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400929#if ENABLE_PRINTF
930 BLTIN("printf" , builtin_printf , NULL),
931#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200932 BLTIN("pwd" , builtin_pwd , NULL),
933 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000934};
935
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000936
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000937/* Debug printouts.
938 */
939#if HUSH_DEBUG
940/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100941# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000942# define debug_enter() (G.debug_indent++)
943# define debug_leave() (G.debug_indent--)
944#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200945# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000946# define debug_enter() ((void)0)
947# define debug_leave() ((void)0)
948#endif
949
950#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100951# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000952#endif
953
954#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100955# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000956#endif
957
958#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100959#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000960#endif
961
962#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100963# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000964#endif
965
966#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100967# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000968# define DEBUG_JOBS 1
969#else
970# define DEBUG_JOBS 0
971#endif
972
973#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100974# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000975# define DEBUG_EXPAND 1
976#else
977# define DEBUG_EXPAND 0
978#endif
979
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200980#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100981# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200982#endif
983
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000984#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100985# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000986# define DEBUG_GLOB 1
987#else
988# define DEBUG_GLOB 0
989#endif
990
991#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100992# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000993#endif
994
995#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100996# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000997#endif
998
999#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001000# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001001# define DEBUG_CLEAN 1
1002#else
1003# define DEBUG_CLEAN 0
1004#endif
1005
1006#if DEBUG_EXPAND
1007static void debug_print_strings(const char *prefix, char **vv)
1008{
1009 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001010 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001011 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001012 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001013}
1014#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001015# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001016#endif
1017
1018
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001019/* Leak hunting. Use hush_leaktool.sh for post-processing.
1020 */
1021#if LEAK_HUNTING
1022static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001023{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001024 void *ptr = xmalloc((size + 0xff) & ~0xff);
1025 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1026 return ptr;
1027}
1028static void *xxrealloc(int lineno, void *ptr, size_t size)
1029{
1030 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1031 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1032 return ptr;
1033}
1034static char *xxstrdup(int lineno, const char *str)
1035{
1036 char *ptr = xstrdup(str);
1037 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1038 return ptr;
1039}
1040static void xxfree(void *ptr)
1041{
1042 fdprintf(2, "free %p\n", ptr);
1043 free(ptr);
1044}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001045# define xmalloc(s) xxmalloc(__LINE__, s)
1046# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1047# define xstrdup(s) xxstrdup(__LINE__, s)
1048# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001049#endif
1050
1051
1052/* Syntax and runtime errors. They always abort scripts.
1053 * In interactive use they usually discard unparsed and/or unexecuted commands
1054 * and return to the prompt.
1055 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1056 */
1057#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001058# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001059# define syntax_error(lineno, msg) syntax_error(msg)
1060# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1061# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1062# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1063# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001064#endif
1065
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001066static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001067{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001068 va_list p;
1069
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001070#if HUSH_DEBUG >= 2
1071 bb_error_msg("hush.c:%u", lineno);
1072#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001073 va_start(p, fmt);
1074 bb_verror_msg(fmt, p, NULL);
1075 va_end(p);
1076 if (!G_interactive_fd)
1077 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001078}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001079
1080static void syntax_error(unsigned lineno, const char *msg)
1081{
1082 if (msg)
1083 die_if_script(lineno, "syntax error: %s", msg);
1084 else
1085 die_if_script(lineno, "syntax error", NULL);
1086}
1087
1088static void syntax_error_at(unsigned lineno, const char *msg)
1089{
1090 die_if_script(lineno, "syntax error at '%s'", msg);
1091}
1092
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001093static void syntax_error_unterm_str(unsigned lineno, const char *s)
1094{
1095 die_if_script(lineno, "syntax error: unterminated %s", s);
1096}
1097
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001098/* It so happens that all such cases are totally fatal
1099 * even if shell is interactive: EOF while looking for closing
1100 * delimiter. There is nowhere to read stuff from after that,
1101 * it's EOF! The only choice is to terminate.
1102 */
1103static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001104static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001105{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001106 char msg[2] = { ch, '\0' };
1107 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001108 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001109}
1110
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001111static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001112{
1113 char msg[2];
1114 msg[0] = ch;
1115 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001116 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001117}
1118
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001119#if HUSH_DEBUG < 2
1120# undef die_if_script
1121# undef syntax_error
1122# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001123# undef syntax_error_unterm_ch
1124# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001125# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001126#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001127# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001128# define syntax_error(msg) syntax_error(__LINE__, msg)
1129# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1130# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1131# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1132# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001133#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001134
Denis Vlasenko552433b2009-04-04 19:29:21 +00001135
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001136#if ENABLE_HUSH_INTERACTIVE
1137static void cmdedit_update_prompt(void);
1138#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001139# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001140#endif
1141
1142
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001143/* Utility functions
1144 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001145/* Replace each \x with x in place, return ptr past NUL. */
1146static char *unbackslash(char *src)
1147{
Denys Vlasenko71885402009-09-24 01:44:13 +02001148 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001149 while (1) {
1150 if (*src == '\\')
1151 src++;
1152 if ((*dst++ = *src++) == '\0')
1153 break;
1154 }
1155 return dst;
1156}
1157
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001158static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001159{
1160 int i;
1161 unsigned count1;
1162 unsigned count2;
1163 char **v;
1164
1165 v = strings;
1166 count1 = 0;
1167 if (v) {
1168 while (*v) {
1169 count1++;
1170 v++;
1171 }
1172 }
1173 count2 = 0;
1174 v = add;
1175 while (*v) {
1176 count2++;
1177 v++;
1178 }
1179 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1180 v[count1 + count2] = NULL;
1181 i = count2;
1182 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001183 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001184 return v;
1185}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001186#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001187static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1188{
1189 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1190 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1191 return ptr;
1192}
1193#define add_strings_to_strings(strings, add, need_to_dup) \
1194 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1195#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001196
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001197/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001198static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001199{
1200 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001201 v[0] = add;
1202 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001203 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001204}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001205#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001206static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1207{
1208 char **ptr = add_string_to_strings(strings, add);
1209 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1210 return ptr;
1211}
1212#define add_string_to_strings(strings, add) \
1213 xx_add_string_to_strings(__LINE__, strings, add)
1214#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001215
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001216static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001217{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001218 char **v;
1219
1220 if (!strings)
1221 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001222 v = strings;
1223 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001224 free(*v);
1225 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001226 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001227 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001228}
1229
Denis Vlasenko76d50412008-06-10 16:19:39 +00001230
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001231/* Helpers for setting new $n and restoring them back
1232 */
1233typedef struct save_arg_t {
1234 char *sv_argv0;
1235 char **sv_g_argv;
1236 int sv_g_argc;
1237 smallint sv_g_malloced;
1238} save_arg_t;
1239
1240static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1241{
1242 int n;
1243
1244 sv->sv_argv0 = argv[0];
1245 sv->sv_g_argv = G.global_argv;
1246 sv->sv_g_argc = G.global_argc;
1247 sv->sv_g_malloced = G.global_args_malloced;
1248
1249 argv[0] = G.global_argv[0]; /* retain $0 */
1250 G.global_argv = argv;
1251 G.global_args_malloced = 0;
1252
1253 n = 1;
1254 while (*++argv)
1255 n++;
1256 G.global_argc = n;
1257}
1258
1259static void restore_G_args(save_arg_t *sv, char **argv)
1260{
1261 char **pp;
1262
1263 if (G.global_args_malloced) {
1264 /* someone ran "set -- arg1 arg2 ...", undo */
1265 pp = G.global_argv;
1266 while (*++pp) /* note: does not free $0 */
1267 free(*pp);
1268 free(G.global_argv);
1269 }
1270 argv[0] = sv->sv_argv0;
1271 G.global_argv = sv->sv_g_argv;
1272 G.global_argc = sv->sv_g_argc;
1273 G.global_args_malloced = sv->sv_g_malloced;
1274}
1275
1276
Denis Vlasenkod5762932009-03-31 11:22:57 +00001277/* Basic theory of signal handling in shell
1278 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001279 * This does not describe what hush does, rather, it is current understanding
1280 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001281 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1282 *
1283 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1284 * is finished or backgrounded. It is the same in interactive and
1285 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001286 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001287 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001288 * backgrounds (i.e. stops) or kills all members of currently running
1289 * pipe.
1290 *
1291 * Wait builtin in interruptible by signals for which user trap is set
1292 * or by SIGINT in interactive shell.
1293 *
1294 * Trap handlers will execute even within trap handlers. (right?)
1295 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001296 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1297 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001298 *
1299 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001300 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001301 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001302 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001303 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001304 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001305 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001306 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001307 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001308 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001309 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001310 *
1311 * SIGQUIT: ignore
1312 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001313 * SIGHUP (interactive):
1314 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001315 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001316 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1317 * that all pipe members are stopped. Try this in bash:
1318 * while :; do :; done - ^Z does not background it
1319 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001320 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001321 * of the command line, show prompt. NB: ^C does not send SIGINT
1322 * to interactive shell while shell is waiting for a pipe,
1323 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001324 * Example 1: this waits 5 sec, but does not execute ls:
1325 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1326 * Example 2: this does not wait and does not execute ls:
1327 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1328 * Example 3: this does not wait 5 sec, but executes ls:
1329 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001330 *
1331 * (What happens to signals which are IGN on shell start?)
1332 * (What happens with signal mask on shell start?)
1333 *
1334 * Implementation in hush
1335 * ======================
1336 * We use in-kernel pending signal mask to determine which signals were sent.
1337 * We block all signals which we don't want to take action immediately,
1338 * i.e. we block all signals which need to have special handling as described
1339 * above, and all signals which have traps set.
1340 * After each pipe execution, we extract any pending signals via sigtimedwait()
1341 * and act on them.
1342 *
1343 * unsigned non_DFL_mask: a mask of such "special" signals
1344 * sigset_t blocked_set: current blocked signal set
1345 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001346 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001347 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001348 * "trap 'cmd' SIGxxx":
1349 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001350 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001351 * unblock signals with special interactive handling
1352 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001353 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001354 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001355 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001356 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001357 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001358 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001359 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001360 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001361 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001362 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001363 * Standard says "When a subshell is entered, traps that are not being ignored
1364 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001365 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001366 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001367enum {
1368 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001369 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001370 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001371 | (1 << SIGHUP)
1372 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001373 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001374#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001375 | (1 << SIGTTIN)
1376 | (1 << SIGTTOU)
1377 | (1 << SIGTSTP)
1378#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001379};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001380
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001381#if ENABLE_HUSH_FAST
1382static void SIGCHLD_handler(int sig UNUSED_PARAM)
1383{
1384 G.count_SIGCHLD++;
1385//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1386}
1387#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001388
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001389#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001390
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001391/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001392# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001393/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001394# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001395
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001396/* Restores tty foreground process group, and exits.
1397 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001398 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001399 * or called directly with -EXITCODE.
1400 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001401static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001402static void sigexit(int sig)
1403{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001404 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001405 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001406
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001407 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001408 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001409 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1410 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001411
1412 /* Not a signal, just exit */
1413 if (sig <= 0)
1414 _exit(- sig);
1415
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001416 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001417}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001418#else
1419
Denys Vlasenko8391c482010-05-22 17:50:43 +02001420# define disable_restore_tty_pgrp_on_exit() ((void)0)
1421# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001422
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001423#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001424
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001425/* Restores tty foreground process group, and exits. */
1426static void hush_exit(int exitcode) NORETURN;
1427static void hush_exit(int exitcode)
1428{
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001429 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001430 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1431 /* Prevent recursion:
1432 * trap "echo Hi; exit" EXIT; exit
1433 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001434 char *argv[3];
1435 /* argv[0] is unused */
1436 argv[1] = G.traps[0];
1437 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001438 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001439 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001440 * "trap" will still show it, if executed
1441 * in the handler */
1442 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001443 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001444
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001445#if ENABLE_FEATURE_CLEAN_UP
1446 {
1447 struct variable *cur_var;
1448 if (G.cwd != bb_msg_unknown)
1449 free((char*)G.cwd);
1450 cur_var = G.top_var;
1451 while (cur_var) {
1452 struct variable *tmp = cur_var;
1453 if (!cur_var->max_len)
1454 free(cur_var->varstr);
1455 cur_var = cur_var->next;
1456 free(tmp);
1457 }
1458 }
1459#endif
1460
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001461#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001462 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001463 sigexit(- (exitcode & 0xff));
1464#else
1465 exit(exitcode);
1466#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001467}
1468
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001469
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001470static int check_and_run_traps(int sig)
1471{
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001472 /* I want it in rodata, not in bss.
1473 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1474 * initializer. But other compilers may still use bss.
1475 * TODO: find more portable solution.
1476 */
1477 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001478 smalluint save_rcode;
1479 int last_sig = 0;
1480
1481 if (sig)
1482 goto jump_in;
1483 while (1) {
1484 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1485 if (sig <= 0)
1486 break;
1487 jump_in:
1488 last_sig = sig;
1489 if (G.traps && G.traps[sig]) {
1490 if (G.traps[sig][0]) {
1491 /* We have user-defined handler */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001492 char *argv[3];
1493 /* argv[0] is unused */
1494 argv[1] = G.traps[sig];
1495 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001496 save_rcode = G.last_exitcode;
1497 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001498 G.last_exitcode = save_rcode;
1499 } /* else: "" trap, ignoring signal */
1500 continue;
1501 }
1502 /* not a trap: special action */
1503 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001504#if ENABLE_HUSH_FAST
1505 case SIGCHLD:
1506 G.count_SIGCHLD++;
1507//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1508 break;
1509#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001510 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001511 /* Builtin was ^C'ed, make it look prettier: */
1512 bb_putchar('\n');
1513 G.flag_SIGINT = 1;
1514 break;
1515#if ENABLE_HUSH_JOB
1516 case SIGHUP: {
1517 struct pipe *job;
1518 /* bash is observed to signal whole process groups,
1519 * not individual processes */
1520 for (job = G.job_list; job; job = job->next) {
1521 if (job->pgrp <= 0)
1522 continue;
1523 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1524 if (kill(- job->pgrp, SIGHUP) == 0)
1525 kill(- job->pgrp, SIGCONT);
1526 }
1527 sigexit(SIGHUP);
1528 }
1529#endif
1530 default: /* ignored: */
1531 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1532 break;
1533 }
1534 }
1535 return last_sig;
1536}
1537
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001538
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001539static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001540{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001541 if (force || G.cwd == NULL) {
1542 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1543 * we must not try to free(bb_msg_unknown) */
1544 if (G.cwd == bb_msg_unknown)
1545 G.cwd = NULL;
1546 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1547 if (!G.cwd)
1548 G.cwd = bb_msg_unknown;
1549 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001550 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001551}
1552
Denis Vlasenko83506862007-11-23 13:11:42 +00001553
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001554/*
1555 * Shell and environment variable support
1556 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001557static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001558{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001559 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001560 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001561
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001562 pp = &G.top_var;
1563 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001564 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001565 return pp;
1566 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001567 }
1568 return NULL;
1569}
1570
Denys Vlasenko03dad222010-01-12 23:29:57 +01001571static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001572{
Denys Vlasenko29082232010-07-16 13:52:32 +02001573 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001574 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001575
1576 if (G.expanded_assignments) {
1577 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001578 while (*cpp) {
1579 char *cp = *cpp;
1580 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1581 return cp + len + 1;
1582 cpp++;
1583 }
1584 }
1585
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001586 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001587 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001588 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001589
Denys Vlasenkodea47882009-10-09 15:40:49 +02001590 if (strcmp(name, "PPID") == 0)
1591 return utoa(G.root_ppid);
1592 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001593#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001594 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001595 return utoa(next_random(&G.random_gen));
1596#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001597 return NULL;
1598}
1599
1600/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001601 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001602 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001603 * 0: do not change export flag
1604 * (if creating new variable, flag will be 0)
1605 * 1: set export flag and putenv the variable
1606 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001607 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001608 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001609#if !BB_MMU && ENABLE_HUSH_LOCAL
1610/* all params are used */
1611#elif BB_MMU && ENABLE_HUSH_LOCAL
1612#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1613 set_local_var(str, flg_export, local_lvl)
1614#elif BB_MMU && !ENABLE_HUSH_LOCAL
1615#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001616 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001617#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1618#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1619 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001620#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001621static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001622{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001623 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001624 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001625 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001626 int name_len;
1627
Denis Vlasenko950bd722009-04-21 11:23:56 +00001628 eq_sign = strchr(str, '=');
1629 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001630 free(str);
1631 return -1;
1632 }
1633
Denis Vlasenko950bd722009-04-21 11:23:56 +00001634 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001635 var_pp = &G.top_var;
1636 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001637 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001638 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001639 continue;
1640 }
1641 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001642 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001643#if !BB_MMU
1644 if (!flg_read_only)
1645#endif
1646 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001647 free(str);
1648 return -1;
1649 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001650 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001651 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1652 *eq_sign = '\0';
1653 unsetenv(str);
1654 *eq_sign = '=';
1655 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001656#if ENABLE_HUSH_LOCAL
1657 if (cur->func_nest_level < local_lvl) {
1658 /* New variable is declared as local,
1659 * and existing one is global, or local
1660 * from enclosing function.
1661 * Remove and save old one: */
1662 *var_pp = cur->next;
1663 cur->next = *G.shadowed_vars_pp;
1664 *G.shadowed_vars_pp = cur;
1665 /* bash 3.2.33(1) and exported vars:
1666 * # export z=z
1667 * # f() { local z=a; env | grep ^z; }
1668 * # f
1669 * z=a
1670 * # env | grep ^z
1671 * z=z
1672 */
1673 if (cur->flg_export)
1674 flg_export = 1;
1675 break;
1676 }
1677#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001678 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001679 free_and_exp:
1680 free(str);
1681 goto exp;
1682 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001683 if (cur->max_len != 0) {
1684 if (cur->max_len >= strlen(str)) {
1685 /* This one is from startup env, reuse space */
1686 strcpy(cur->varstr, str);
1687 goto free_and_exp;
1688 }
1689 } else {
1690 /* max_len == 0 signifies "malloced" var, which we can
1691 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001692 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001693 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001694 cur->max_len = 0;
1695 goto set_str_and_exp;
1696 }
1697
Denys Vlasenko295fef82009-06-03 12:47:26 +02001698 /* Not found - create new variable struct */
1699 cur = xzalloc(sizeof(*cur));
1700#if ENABLE_HUSH_LOCAL
1701 cur->func_nest_level = local_lvl;
1702#endif
1703 cur->next = *var_pp;
1704 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001705
1706 set_str_and_exp:
1707 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001708#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001709 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001710#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001711 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001712 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001713 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001714 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1715 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001716 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001717 if (flg_export == -1) {
1718 cur->flg_export = 0;
1719 /* unsetenv was already done */
1720 } else {
1721 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1722 return putenv(cur->varstr);
1723 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001724 }
1725 return 0;
1726}
1727
Denys Vlasenko6db47842009-09-05 20:15:17 +02001728/* Used at startup and after each cd */
1729static void set_pwd_var(int exp)
1730{
1731 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1732 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1733}
1734
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001735static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001736{
1737 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001738 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001739
1740 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001741 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001742 var_pp = &G.top_var;
1743 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001744 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1745 if (cur->flg_read_only) {
1746 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001747 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001748 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001749 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001750 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1751 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001752 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1753 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001754 if (!cur->max_len)
1755 free(cur->varstr);
1756 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001757 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001758 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001759 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001760 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001761 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001762}
1763
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001764static int unset_local_var(const char *name)
1765{
1766 return unset_local_var_len(name, strlen(name));
1767}
1768
1769static void unset_vars(char **strings)
1770{
1771 char **v;
1772
1773 if (!strings)
1774 return;
1775 v = strings;
1776 while (*v) {
1777 const char *eq = strchrnul(*v, '=');
1778 unset_local_var_len(*v, (int)(eq - *v));
1779 v++;
1780 }
1781 free(strings);
1782}
1783
Denys Vlasenko03dad222010-01-12 23:29:57 +01001784static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001785{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001786 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001787 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001788}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001789
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001790
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001791/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001792 * Helpers for "var1=val1 var2=val2 cmd" feature
1793 */
1794static void add_vars(struct variable *var)
1795{
1796 struct variable *next;
1797
1798 while (var) {
1799 next = var->next;
1800 var->next = G.top_var;
1801 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001802 if (var->flg_export) {
1803 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001804 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001805 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001806 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001807 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001808 var = next;
1809 }
1810}
1811
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001812static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001813{
1814 char **s;
1815 struct variable *old = NULL;
1816
1817 if (!strings)
1818 return old;
1819 s = strings;
1820 while (*s) {
1821 struct variable *var_p;
1822 struct variable **var_pp;
1823 char *eq;
1824
1825 eq = strchr(*s, '=');
1826 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001827 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001828 if (var_pp) {
1829 /* Remove variable from global linked list */
1830 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001831 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001832 *var_pp = var_p->next;
1833 /* Add it to returned list */
1834 var_p->next = old;
1835 old = var_p;
1836 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001837 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001838 }
1839 s++;
1840 }
1841 return old;
1842}
1843
1844
1845/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001846 * in_str support
1847 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001848static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001849{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001850 int ch = *i->p;
1851 if (ch != '\0') {
1852 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001853 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001854 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001855 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001856}
1857
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001858static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001859{
1860 return *i->p;
1861}
1862
1863#if ENABLE_HUSH_INTERACTIVE
1864
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001865static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001866{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001867 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001868 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001869 if (G.PS1 == NULL)
1870 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001871 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001872 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001873 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001874 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001875 if (G.PS2 == NULL)
1876 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001877}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001878
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001879static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001880{
1881 const char *prompt_str;
1882 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001883 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1884 /* Set up the prompt */
1885 if (promptmode == 0) { /* PS1 */
1886 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001887 /* bash uses $PWD value, even if it is set by user.
1888 * It uses current dir only if PWD is unset.
1889 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001890 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001891 prompt_str = G.PS1;
1892 } else
1893 prompt_str = G.PS2;
1894 } else
1895 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001896 debug_printf("result '%s'\n", prompt_str);
1897 return prompt_str;
1898}
1899
1900static void get_user_input(struct in_str *i)
1901{
1902 int r;
1903 const char *prompt_str;
1904
1905 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001906# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001907 /* Enable command line editing only while a command line
1908 * is actually being read */
1909 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01001910 /* Unicode support should be activated even if LANG is set
1911 * _during_ shell execution, not only if it was set when
1912 * shell was started. Therefore, re-check LANG every time:
1913 */
1914 reinit_unicode(get_local_var_value("LANG"));
1915
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001916 G.flag_SIGINT = 0;
1917 /* buglet: SIGINT will not make new prompt to appear _at once_,
1918 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01001919 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001920 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001921 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001922 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001923 i->eof_flag = (r < 0);
1924 if (i->eof_flag) { /* EOF/error detected */
1925 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1926 G.user_input_buf[1] = '\0';
1927 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001928# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001929 do {
1930 G.flag_SIGINT = 0;
1931 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001932 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001933 G.user_input_buf[0] = r = fgetc(i->file);
1934 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001935//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001936 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001937 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001938# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001939 i->p = G.user_input_buf;
1940}
1941
1942#endif /* INTERACTIVE */
1943
1944/* This is the magic location that prints prompts
1945 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001946static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001947{
1948 int ch;
1949
1950 /* If there is data waiting, eat it up */
1951 if (i->p && *i->p) {
1952#if ENABLE_HUSH_INTERACTIVE
1953 take_cached:
1954#endif
1955 ch = *i->p++;
1956 if (i->eof_flag && !*i->p)
1957 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001958 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001959 } else {
1960 /* need to double check i->file because we might be doing something
1961 * more complicated by now, like sourcing or substituting. */
1962#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01001963 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001964 do {
1965 get_user_input(i);
1966 } while (!*i->p); /* need non-empty line */
1967 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001968 goto take_cached;
1969 }
1970#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001971 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001972 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001973 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001974 return ch;
1975}
1976
Denis Vlasenko913a2012009-04-05 22:17:04 +00001977/* All callers guarantee this routine will never
1978 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001979 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001980static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001981{
1982 int ch;
1983 if (i->p && *i->p) {
1984 if (i->eof_flag && !i->p[1])
1985 return EOF;
1986 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001987 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001988 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001989 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001990 i->eof_flag = (ch == EOF);
1991 i->peek_buf[0] = ch;
1992 i->peek_buf[1] = '\0';
1993 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001994 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001995 return ch;
1996}
1997
1998static void setup_file_in_str(struct in_str *i, FILE *f)
1999{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002000 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002001 i->peek = file_peek;
2002 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002003 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002004 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002005 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002006}
2007
2008static void setup_string_in_str(struct in_str *i, const char *s)
2009{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002010 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002011 i->peek = static_peek;
2012 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002013 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002014 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002015 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002016}
2017
2018
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002019/*
2020 * o_string support
2021 */
2022#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002023
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002024static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002025{
2026 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002027 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002028 if (o->data)
2029 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002030}
2031
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002032static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002033{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002034 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002035 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002036}
2037
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002038static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2039{
2040 free(o->data);
2041}
2042
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002043static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002044{
2045 if (o->length + len > o->maxlen) {
2046 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2047 o->data = xrealloc(o->data, 1 + o->maxlen);
2048 }
2049}
2050
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002051static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002052{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002053 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2054 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002055 o->data[o->length] = ch;
2056 o->length++;
2057 o->data[o->length] = '\0';
2058}
2059
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002060static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002061{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002062 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002063 memcpy(&o->data[o->length], str, len);
2064 o->length += len;
2065 o->data[o->length] = '\0';
2066}
2067
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002068static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002069{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002070 o_addblock(o, str, strlen(str));
2071}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002072
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002073#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002074static void nommu_addchr(o_string *o, int ch)
2075{
2076 if (o)
2077 o_addchr(o, ch);
2078}
2079#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002080# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002081#endif
2082
2083static void o_addstr_with_NUL(o_string *o, const char *str)
2084{
2085 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002086}
2087
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002088/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002089 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002090 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2091 * Apparently, on unquoted $v bash still does globbing
2092 * ("v='*.txt'; echo $v" prints all .txt files),
2093 * but NOT brace expansion! Thus, there should be TWO independent
2094 * quoting mechanisms on $v expansion side: one protects
2095 * $v from brace expansion, and other additionally protects "$v" against globbing.
2096 * We have only second one.
2097 */
2098
Denys Vlasenko9e800222010-10-03 14:28:04 +02002099#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002100# define MAYBE_BRACES "{}"
2101#else
2102# define MAYBE_BRACES ""
2103#endif
2104
Eric Andersen25f27032001-04-26 23:22:31 +00002105/* My analysis of quoting semantics tells me that state information
2106 * is associated with a destination, not a source.
2107 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002108static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002109{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002110 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002111 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002112 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002113 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002114 o_grow_by(o, sz);
2115 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002116 o->data[o->length] = '\\';
2117 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002118 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002119 o->data[o->length] = ch;
2120 o->length++;
2121 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002122}
2123
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002124static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002125{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002126 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002127 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2128 && strchr("*?[\\" MAYBE_BRACES, ch)
2129 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002130 sz++;
2131 o->data[o->length] = '\\';
2132 o->length++;
2133 }
2134 o_grow_by(o, sz);
2135 o->data[o->length] = ch;
2136 o->length++;
2137 o->data[o->length] = '\0';
2138}
2139
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002140static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002141{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002142 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002143 char ch;
2144 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002145 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002146 if (ordinary_cnt > len) /* paranoia */
2147 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002148 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002149 if (ordinary_cnt == len)
2150 return;
2151 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002152 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002153
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002154 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002155 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002156 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002157 sz++;
2158 o->data[o->length] = '\\';
2159 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002160 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002161 o_grow_by(o, sz);
2162 o->data[o->length] = ch;
2163 o->length++;
2164 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002165 }
2166}
2167
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002168static void o_addQblock(o_string *o, const char *str, int len)
2169{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002170 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002171 o_addblock(o, str, len);
2172 return;
2173 }
2174 o_addqblock(o, str, len);
2175}
2176
Denys Vlasenko38292b62010-09-05 14:49:40 +02002177static void o_addQstr(o_string *o, const char *str)
2178{
2179 o_addQblock(o, str, strlen(str));
2180}
2181
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002182/* A special kind of o_string for $VAR and `cmd` expansion.
2183 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002184 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002185 * list[i] contains an INDEX (int!) into this string data.
2186 * It means that if list[] needs to grow, data needs to be moved higher up
2187 * but list[i]'s need not be modified.
2188 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002189 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002190 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2191 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002192#if DEBUG_EXPAND || DEBUG_GLOB
2193static void debug_print_list(const char *prefix, o_string *o, int n)
2194{
2195 char **list = (char**)o->data;
2196 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2197 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002198
2199 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002200 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002201 prefix, list, n, string_start, o->length, o->maxlen,
2202 !!(o->o_expflags & EXP_FLAG_GLOB),
2203 o->has_quoted_part,
2204 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002205 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002206 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002207 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2208 o->data + (int)(uintptr_t)list[i] + string_start,
2209 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002210 i++;
2211 }
2212 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002213 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002214 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002215 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002216 }
2217}
2218#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002219# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002220#endif
2221
2222/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2223 * in list[n] so that it points past last stored byte so far.
2224 * It returns n+1. */
2225static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002226{
2227 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002228 int string_start;
2229 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002230
2231 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002232 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2233 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002234 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002235 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002236 /* list[n] points to string_start, make space for 16 more pointers */
2237 o->maxlen += 0x10 * sizeof(list[0]);
2238 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002239 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002240 memmove(list + n + 0x10, list + n, string_len);
2241 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002242 } else {
2243 debug_printf_list("list[%d]=%d string_start=%d\n",
2244 n, string_len, string_start);
2245 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002246 } else {
2247 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002248 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2249 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002250 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2251 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002252 o->has_empty_slot = 0;
2253 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002254 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002255 return n + 1;
2256}
2257
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002258/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002259static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002260{
2261 char **list = (char**)o->data;
2262 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2263
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002264 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002265}
2266
Denys Vlasenko9e800222010-10-03 14:28:04 +02002267#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002268/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2269 * first, it processes even {a} (no commas), second,
2270 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002271 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002272 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002273
2274/* Helper */
2275static int glob_needed(const char *s)
2276{
2277 while (*s) {
2278 if (*s == '\\') {
2279 if (!s[1])
2280 return 0;
2281 s += 2;
2282 continue;
2283 }
2284 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2285 return 1;
2286 s++;
2287 }
2288 return 0;
2289}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002290/* Return pointer to next closing brace or to comma */
2291static const char *next_brace_sub(const char *cp)
2292{
2293 unsigned depth = 0;
2294 cp++;
2295 while (*cp != '\0') {
2296 if (*cp == '\\') {
2297 if (*++cp == '\0')
2298 break;
2299 cp++;
2300 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002301 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002302 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002303 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002304 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002305 depth++;
2306 }
2307
2308 return *cp != '\0' ? cp : NULL;
2309}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002310/* Recursive brace globber. Note: may garble pattern[]. */
2311static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002312{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002313 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002314 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002315 const char *next;
2316 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002317 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002318 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002319
2320 debug_printf_glob("glob_brace('%s')\n", pattern);
2321
2322 begin = pattern;
2323 while (1) {
2324 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002325 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002326 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002327 /* Find the first sub-pattern and at the same time
2328 * find the rest after the closing brace */
2329 next = next_brace_sub(begin);
2330 if (next == NULL) {
2331 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002332 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002333 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002334 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002335 /* "{abc}" with no commas - illegal
2336 * brace expr, disregard and skip it */
2337 begin = next + 1;
2338 continue;
2339 }
2340 break;
2341 }
2342 if (*begin == '\\' && begin[1] != '\0')
2343 begin++;
2344 begin++;
2345 }
2346 debug_printf_glob("begin:%s\n", begin);
2347 debug_printf_glob("next:%s\n", next);
2348
2349 /* Now find the end of the whole brace expression */
2350 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002351 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002352 rest = next_brace_sub(rest);
2353 if (rest == NULL) {
2354 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002355 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002356 }
2357 debug_printf_glob("rest:%s\n", rest);
2358 }
2359 rest_len = strlen(++rest) + 1;
2360
2361 /* We are sure the brace expression is well-formed */
2362
2363 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002364 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002365
2366 /* We have a brace expression. BEGIN points to the opening {,
2367 * NEXT points past the terminator of the first element, and REST
2368 * points past the final }. We will accumulate result names from
2369 * recursive runs for each brace alternative in the buffer using
2370 * GLOB_APPEND. */
2371
2372 p = begin + 1;
2373 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002374 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002375 memcpy(
2376 mempcpy(
2377 mempcpy(new_pattern_buf,
2378 /* We know the prefix for all sub-patterns */
2379 pattern, begin - pattern),
2380 p, next - p),
2381 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002382
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002383 /* Note: glob_brace() may garble new_pattern_buf[].
2384 * That's why we re-copy prefix every time (1st memcpy above).
2385 */
2386 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002387 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002388 /* We saw the last entry */
2389 break;
2390 }
2391 p = next + 1;
2392 next = next_brace_sub(next);
2393 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002394 free(new_pattern_buf);
2395 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002396
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002397 simple_glob:
2398 {
2399 int gr;
2400 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002401
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002402 memset(&globdata, 0, sizeof(globdata));
2403 gr = glob(pattern, 0, NULL, &globdata);
2404 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2405 if (gr != 0) {
2406 if (gr == GLOB_NOMATCH) {
2407 globfree(&globdata);
2408 /* NB: garbles parameter */
2409 unbackslash(pattern);
2410 o_addstr_with_NUL(o, pattern);
2411 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2412 return o_save_ptr_helper(o, n);
2413 }
2414 if (gr == GLOB_NOSPACE)
2415 bb_error_msg_and_die(bb_msg_memory_exhausted);
2416 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2417 * but we didn't specify it. Paranoia again. */
2418 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2419 }
2420 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2421 char **argv = globdata.gl_pathv;
2422 while (1) {
2423 o_addstr_with_NUL(o, *argv);
2424 n = o_save_ptr_helper(o, n);
2425 argv++;
2426 if (!*argv)
2427 break;
2428 }
2429 }
2430 globfree(&globdata);
2431 }
2432 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002433}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002434/* Performs globbing on last list[],
2435 * saving each result as a new list[].
2436 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002437static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002438{
2439 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002440
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002441 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002442 if (!o->data)
2443 return o_save_ptr_helper(o, n);
2444 pattern = o->data + o_get_last_ptr(o, n);
2445 debug_printf_glob("glob pattern '%s'\n", pattern);
2446 if (!glob_needed(pattern)) {
2447 /* unbackslash last string in o in place, fix length */
2448 o->length = unbackslash(pattern) - o->data;
2449 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2450 return o_save_ptr_helper(o, n);
2451 }
2452
2453 copy = xstrdup(pattern);
2454 /* "forget" pattern in o */
2455 o->length = pattern - o->data;
2456 n = glob_brace(copy, o, n);
2457 free(copy);
2458 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002459 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002460 return n;
2461}
2462
Denys Vlasenko238081f2010-10-03 14:26:26 +02002463#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002464
2465/* Helper */
2466static int glob_needed(const char *s)
2467{
2468 while (*s) {
2469 if (*s == '\\') {
2470 if (!s[1])
2471 return 0;
2472 s += 2;
2473 continue;
2474 }
2475 if (*s == '*' || *s == '[' || *s == '?')
2476 return 1;
2477 s++;
2478 }
2479 return 0;
2480}
2481/* Performs globbing on last list[],
2482 * saving each result as a new list[].
2483 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002484static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002485{
2486 glob_t globdata;
2487 int gr;
2488 char *pattern;
2489
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002490 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002491 if (!o->data)
2492 return o_save_ptr_helper(o, n);
2493 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002494 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002495 if (!glob_needed(pattern)) {
2496 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002497 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002498 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002499 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002500 return o_save_ptr_helper(o, n);
2501 }
2502
2503 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002504 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2505 * If we glob "*.\*" and don't find anything, we need
2506 * to fall back to using literal "*.*", but GLOB_NOCHECK
2507 * will return "*.\*"!
2508 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002509 gr = glob(pattern, 0, NULL, &globdata);
2510 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002511 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002512 if (gr == GLOB_NOMATCH) {
2513 globfree(&globdata);
2514 goto literal;
2515 }
2516 if (gr == GLOB_NOSPACE)
2517 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002518 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2519 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002520 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002521 }
2522 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2523 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002524 /* "forget" pattern in o */
2525 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002526 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002527 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002528 n = o_save_ptr_helper(o, n);
2529 argv++;
2530 if (!*argv)
2531 break;
2532 }
2533 }
2534 globfree(&globdata);
2535 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002536 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002537 return n;
2538}
2539
Denys Vlasenko238081f2010-10-03 14:26:26 +02002540#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002541
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002542/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002543 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002544static int o_save_ptr(o_string *o, int n)
2545{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002546 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002547 /* If o->has_empty_slot, list[n] was already globbed
2548 * (if it was requested back then when it was filled)
2549 * so don't do that again! */
2550 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002551 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002552 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002553 return o_save_ptr_helper(o, n);
2554}
2555
2556/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002557static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002558{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002559 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002560 int string_start;
2561
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002562 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2563 if (DEBUG_EXPAND)
2564 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002565 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002566 list = (char**)o->data;
2567 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2568 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002569 while (n) {
2570 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002571 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002572 }
2573 return list;
2574}
2575
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002576static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002577
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002578/* Returns pi->next - next pipe in the list */
2579static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002580{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002581 struct pipe *next;
2582 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002583
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002584 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002585 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002586 struct command *command;
2587 struct redir_struct *r, *rnext;
2588
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002589 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002590 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002591 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002592 if (DEBUG_CLEAN) {
2593 int a;
2594 char **p;
2595 for (a = 0, p = command->argv; *p; a++, p++) {
2596 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2597 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002598 }
2599 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002600 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002601 }
2602 /* not "else if": on syntax error, we may have both! */
2603 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002604 debug_printf_clean(" begin group (cmd_type:%d)\n",
2605 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002606 free_pipe_list(command->group);
2607 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002608 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002609 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002610 /* else is crucial here.
2611 * If group != NULL, child_func is meaningless */
2612#if ENABLE_HUSH_FUNCTIONS
2613 else if (command->child_func) {
2614 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2615 command->child_func->parent_cmd = NULL;
2616 }
2617#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002618#if !BB_MMU
2619 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002620 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002621#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002622 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002623 debug_printf_clean(" redirect %d%s",
2624 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002625 /* guard against the case >$FOO, where foo is unset or blank */
2626 if (r->rd_filename) {
2627 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2628 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002629 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002630 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002631 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002632 rnext = r->next;
2633 free(r);
2634 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002635 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002636 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002637 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002638 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002639#if ENABLE_HUSH_JOB
2640 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002641 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002642#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002643
2644 next = pi->next;
2645 free(pi);
2646 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002647}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002648
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002649static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002650{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002651 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002652#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002653 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002654#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002655 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002656 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002657 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002658}
2659
2660
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002661/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002662
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002663#ifndef debug_print_tree
2664static void debug_print_tree(struct pipe *pi, int lvl)
2665{
2666 static const char *const PIPE[] = {
2667 [PIPE_SEQ] = "SEQ",
2668 [PIPE_AND] = "AND",
2669 [PIPE_OR ] = "OR" ,
2670 [PIPE_BG ] = "BG" ,
2671 };
2672 static const char *RES[] = {
2673 [RES_NONE ] = "NONE" ,
2674# if ENABLE_HUSH_IF
2675 [RES_IF ] = "IF" ,
2676 [RES_THEN ] = "THEN" ,
2677 [RES_ELIF ] = "ELIF" ,
2678 [RES_ELSE ] = "ELSE" ,
2679 [RES_FI ] = "FI" ,
2680# endif
2681# if ENABLE_HUSH_LOOPS
2682 [RES_FOR ] = "FOR" ,
2683 [RES_WHILE] = "WHILE",
2684 [RES_UNTIL] = "UNTIL",
2685 [RES_DO ] = "DO" ,
2686 [RES_DONE ] = "DONE" ,
2687# endif
2688# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2689 [RES_IN ] = "IN" ,
2690# endif
2691# if ENABLE_HUSH_CASE
2692 [RES_CASE ] = "CASE" ,
2693 [RES_CASE_IN ] = "CASE_IN" ,
2694 [RES_MATCH] = "MATCH",
2695 [RES_CASE_BODY] = "CASE_BODY",
2696 [RES_ESAC ] = "ESAC" ,
2697# endif
2698 [RES_XXXX ] = "XXXX" ,
2699 [RES_SNTX ] = "SNTX" ,
2700 };
2701 static const char *const CMDTYPE[] = {
2702 "{}",
2703 "()",
2704 "[noglob]",
2705# if ENABLE_HUSH_FUNCTIONS
2706 "func()",
2707# endif
2708 };
2709
2710 int pin, prn;
2711
2712 pin = 0;
2713 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002714 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002715 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2716 prn = 0;
2717 while (prn < pi->num_cmds) {
2718 struct command *command = &pi->cmds[prn];
2719 char **argv = command->argv;
2720
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002721 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002722 lvl*2, "", prn,
2723 command->assignment_cnt);
2724 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002725 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002726 CMDTYPE[command->cmd_type],
2727 argv
2728# if !BB_MMU
2729 , " group_as_string:", command->group_as_string
2730# else
2731 , "", ""
2732# endif
2733 );
2734 debug_print_tree(command->group, lvl+1);
2735 prn++;
2736 continue;
2737 }
2738 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002739 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002740 argv++;
2741 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002742 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002743 prn++;
2744 }
2745 pi = pi->next;
2746 pin++;
2747 }
2748}
2749#endif /* debug_print_tree */
2750
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002751static struct pipe *new_pipe(void)
2752{
Eric Andersen25f27032001-04-26 23:22:31 +00002753 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002754 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002755 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002756 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002757 return pi;
2758}
2759
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002760/* Command (member of a pipe) is complete, or we start a new pipe
2761 * if ctx->command is NULL.
2762 * No errors possible here.
2763 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002764static int done_command(struct parse_context *ctx)
2765{
2766 /* The command is really already in the pipe structure, so
2767 * advance the pipe counter and make a new, null command. */
2768 struct pipe *pi = ctx->pipe;
2769 struct command *command = ctx->command;
2770
2771 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002772 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002773 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002774 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002775 }
2776 pi->num_cmds++;
2777 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002778 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002779 } else {
2780 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2781 }
2782
2783 /* Only real trickiness here is that the uncommitted
2784 * command structure is not counted in pi->num_cmds. */
2785 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002786 ctx->command = command = &pi->cmds[pi->num_cmds];
2787 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002788 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789 return pi->num_cmds; /* used only for 0/nonzero check */
2790}
2791
2792static void done_pipe(struct parse_context *ctx, pipe_style type)
2793{
2794 int not_null;
2795
2796 debug_printf_parse("done_pipe entered, followup %d\n", type);
2797 /* Close previous command */
2798 not_null = done_command(ctx);
2799 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002800#if HAS_KEYWORDS
2801 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2802 ctx->ctx_inverted = 0;
2803 ctx->pipe->res_word = ctx->ctx_res_w;
2804#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002805
2806 /* Without this check, even just <enter> on command line generates
2807 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002808 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002809 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002810#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002811 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002812#endif
2813#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002814 || ctx->ctx_res_w == RES_DONE
2815 || ctx->ctx_res_w == RES_FOR
2816 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002817#endif
2818#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002819 || ctx->ctx_res_w == RES_ESAC
2820#endif
2821 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002822 struct pipe *new_p;
2823 debug_printf_parse("done_pipe: adding new pipe: "
2824 "not_null:%d ctx->ctx_res_w:%d\n",
2825 not_null, ctx->ctx_res_w);
2826 new_p = new_pipe();
2827 ctx->pipe->next = new_p;
2828 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002829 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002830 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002831 * This is used to control execution.
2832 * RES_FOR and RES_IN are NOT sticky (needed to support
2833 * cases where variable or value happens to match a keyword):
2834 */
2835#if ENABLE_HUSH_LOOPS
2836 if (ctx->ctx_res_w == RES_FOR
2837 || ctx->ctx_res_w == RES_IN)
2838 ctx->ctx_res_w = RES_NONE;
2839#endif
2840#if ENABLE_HUSH_CASE
2841 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002842 ctx->ctx_res_w = RES_CASE_BODY;
2843 if (ctx->ctx_res_w == RES_CASE)
2844 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002845#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002846 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002847 /* Create the memory for command, roughly:
2848 * ctx->pipe->cmds = new struct command;
2849 * ctx->command = &ctx->pipe->cmds[0];
2850 */
2851 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002852 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002853 }
2854 debug_printf_parse("done_pipe return\n");
2855}
2856
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002857static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002858{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002859 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002860 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002861 /* Create the memory for command, roughly:
2862 * ctx->pipe->cmds = new struct command;
2863 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002864 */
2865 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002866}
2867
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002868/* If a reserved word is found and processed, parse context is modified
2869 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002870 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002871#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002872struct reserved_combo {
2873 char literal[6];
2874 unsigned char res;
2875 unsigned char assignment_flag;
2876 int flag;
2877};
2878enum {
2879 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002880# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002881 FLAG_IF = (1 << RES_IF ),
2882 FLAG_THEN = (1 << RES_THEN ),
2883 FLAG_ELIF = (1 << RES_ELIF ),
2884 FLAG_ELSE = (1 << RES_ELSE ),
2885 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002886# endif
2887# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002888 FLAG_FOR = (1 << RES_FOR ),
2889 FLAG_WHILE = (1 << RES_WHILE),
2890 FLAG_UNTIL = (1 << RES_UNTIL),
2891 FLAG_DO = (1 << RES_DO ),
2892 FLAG_DONE = (1 << RES_DONE ),
2893 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002894# endif
2895# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002896 FLAG_MATCH = (1 << RES_MATCH),
2897 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002898# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002899 FLAG_START = (1 << RES_XXXX ),
2900};
2901
2902static const struct reserved_combo* match_reserved_word(o_string *word)
2903{
Eric Andersen25f27032001-04-26 23:22:31 +00002904 /* Mostly a list of accepted follow-up reserved words.
2905 * FLAG_END means we are done with the sequence, and are ready
2906 * to turn the compound list into a command.
2907 * FLAG_START means the word must start a new compound list.
2908 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002909 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002910# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002911 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2912 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2913 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2914 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2915 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2916 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002917# endif
2918# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002919 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2920 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2921 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2922 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2923 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2924 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002925# endif
2926# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002927 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2928 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002929# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002930 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002931 const struct reserved_combo *r;
2932
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02002933 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002934 if (strcmp(word->data, r->literal) == 0)
2935 return r;
2936 }
2937 return NULL;
2938}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002939/* Return 0: not a keyword, 1: keyword
2940 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002941static int reserved_word(o_string *word, struct parse_context *ctx)
2942{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002943# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002944 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002945 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002946 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002947# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002948 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002949
Denys Vlasenko38292b62010-09-05 14:49:40 +02002950 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002951 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002952 r = match_reserved_word(word);
2953 if (!r)
2954 return 0;
2955
2956 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002957# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002958 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2959 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002960 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002961 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002962# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002963 if (r->flag == 0) { /* '!' */
2964 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002965 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002966 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002967 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002968 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002969 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002970 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002971 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002972 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002973
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002974 old = xmalloc(sizeof(*old));
2975 debug_printf_parse("push stack %p\n", old);
2976 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002977 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002978 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002979 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002980 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002981 ctx->ctx_res_w = RES_SNTX;
2982 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002983 } else {
2984 /* "{...} fi" is ok. "{...} if" is not
2985 * Example:
2986 * if { echo foo; } then { echo bar; } fi */
2987 if (ctx->command->group)
2988 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002989 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002990
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002991 ctx->ctx_res_w = r->res;
2992 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002993 word->o_assignment = r->assignment_flag;
2994
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002995 if (ctx->old_flag & FLAG_END) {
2996 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002997
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002998 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002999 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003000 old = ctx->stack;
3001 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003002 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003003# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003004 o_addstr(&old->as_string, ctx->as_string.data);
3005 o_free_unsafe(&ctx->as_string);
3006 old->command->group_as_string = xstrdup(old->as_string.data);
3007 debug_printf_parse("pop, remembering as:'%s'\n",
3008 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003009# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003010 *ctx = *old; /* physical copy */
3011 free(old);
3012 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003013 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003014}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003015#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003016
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003017/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003018 * Normal return is 0. Syntax errors return 1.
3019 * Note: on return, word is reset, but not o_free'd!
3020 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003021static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003022{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003023 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003024
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003025 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003026 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003027 debug_printf_parse("done_word return 0: true null, ignored\n");
3028 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003029 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003030
Eric Andersen25f27032001-04-26 23:22:31 +00003031 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003032 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3033 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003034 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3035 * "2.7 Redirection
3036 * ...the word that follows the redirection operator
3037 * shall be subjected to tilde expansion, parameter expansion,
3038 * command substitution, arithmetic expansion, and quote
3039 * removal. Pathname expansion shall not be performed
3040 * on the word by a non-interactive shell; an interactive
3041 * shell may perform it, but shall do so only when
3042 * the expansion would result in one word."
3043 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003044 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003045 /* Cater for >\file case:
3046 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3047 * Same with heredocs:
3048 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3049 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003050 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3051 unbackslash(ctx->pending_redirect->rd_filename);
3052 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003053 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003054 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3055 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003056 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003057 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003058 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003059 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003060 /* If this word wasn't an assignment, next ones definitely
3061 * can't be assignments. Even if they look like ones. */
3062 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3063 && word->o_assignment != WORD_IS_KEYWORD
3064 ) {
3065 word->o_assignment = NOT_ASSIGNMENT;
3066 } else {
3067 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3068 command->assignment_cnt++;
3069 word->o_assignment = MAYBE_ASSIGNMENT;
3070 }
3071
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003072#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003073# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003074 if (ctx->ctx_dsemicolon
3075 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3076 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003077 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003078 /* ctx->ctx_res_w = RES_MATCH; */
3079 ctx->ctx_dsemicolon = 0;
3080 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003081# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003082 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003083# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003084 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3085 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003086# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003087# if ENABLE_HUSH_CASE
3088 && ctx->ctx_res_w != RES_CASE
3089# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003090 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003091 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003092 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003093 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003094 debug_printf_parse("done_word return %d\n",
3095 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003096 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003097 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003098# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003099 if (strcmp(word->data, "[[") == 0) {
3100 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3101 }
3102 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003103# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003104 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003105#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003106 if (command->group) {
3107 /* "{ echo foo; } echo bar" - bad */
3108 syntax_error_at(word->data);
3109 debug_printf_parse("done_word return 1: syntax error, "
3110 "groups and arglists don't mix\n");
3111 return 1;
3112 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02003113 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003114 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3115 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003116 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003117 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003118 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003119 char *p = word->data;
3120 while (p[0] == SPECIAL_VAR_SYMBOL
3121 && (p[1] & 0x7f) == '@'
3122 && p[2] == SPECIAL_VAR_SYMBOL
3123 ) {
3124 p += 3;
3125 }
3126 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003127 /* saw no "$@", or not only "$@" but some
3128 * real text is there too */
3129 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003130 * e.g. "", $empty"" etc to not disappear */
3131 o_addchr(word, SPECIAL_VAR_SYMBOL);
3132 o_addchr(word, SPECIAL_VAR_SYMBOL);
3133 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003134 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003135 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003136 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003137 }
Eric Andersen25f27032001-04-26 23:22:31 +00003138
Denis Vlasenko06810332007-05-21 23:30:54 +00003139#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003140 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003141 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003142 || !is_well_formed_var_name(command->argv[0], '\0')
3143 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003144 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003145 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003146 return 1;
3147 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003148 /* Force FOR to have just one word (variable name) */
3149 /* NB: basically, this makes hush see "for v in ..."
3150 * syntax as if it is "for v; in ...". FOR and IN become
3151 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003152 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003153 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003154#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003155#if ENABLE_HUSH_CASE
3156 /* Force CASE to have just one word */
3157 if (ctx->ctx_res_w == RES_CASE) {
3158 done_pipe(ctx, PIPE_SEQ);
3159 }
3160#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003161
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003162 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003163
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003164 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003165 return 0;
3166}
3167
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003168
3169/* Peek ahead in the input to find out if we have a "&n" construct,
3170 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003171 * Return:
3172 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3173 * REDIRFD_SYNTAX_ERR if syntax error,
3174 * REDIRFD_TO_FILE if no & was seen,
3175 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003176 */
3177#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003178#define parse_redir_right_fd(as_string, input) \
3179 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003180#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003181static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003182{
3183 int ch, d, ok;
3184
3185 ch = i_peek(input);
3186 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003187 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003188
3189 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003190 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003191 ch = i_peek(input);
3192 if (ch == '-') {
3193 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003194 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003195 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003196 }
3197 d = 0;
3198 ok = 0;
3199 while (ch != EOF && isdigit(ch)) {
3200 d = d*10 + (ch-'0');
3201 ok = 1;
3202 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003203 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003204 ch = i_peek(input);
3205 }
3206 if (ok) return d;
3207
3208//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3209
3210 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003211 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003212}
3213
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003214/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003215 */
3216static int parse_redirect(struct parse_context *ctx,
3217 int fd,
3218 redir_type style,
3219 struct in_str *input)
3220{
3221 struct command *command = ctx->command;
3222 struct redir_struct *redir;
3223 struct redir_struct **redirp;
3224 int dup_num;
3225
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003226 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003227 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003228 /* Check for a '>&1' type redirect */
3229 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3230 if (dup_num == REDIRFD_SYNTAX_ERR)
3231 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003232 } else {
3233 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003234 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003235 if (dup_num) { /* <<-... */
3236 ch = i_getch(input);
3237 nommu_addchr(&ctx->as_string, ch);
3238 ch = i_peek(input);
3239 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003240 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003241
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003242 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003243 int ch = i_peek(input);
3244 if (ch == '|') {
3245 /* >|FILE redirect ("clobbering" >).
3246 * Since we do not support "set -o noclobber" yet,
3247 * >| and > are the same for now. Just eat |.
3248 */
3249 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003250 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003251 }
3252 }
3253
3254 /* Create a new redir_struct and append it to the linked list */
3255 redirp = &command->redirects;
3256 while ((redir = *redirp) != NULL) {
3257 redirp = &(redir->next);
3258 }
3259 *redirp = redir = xzalloc(sizeof(*redir));
3260 /* redir->next = NULL; */
3261 /* redir->rd_filename = NULL; */
3262 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003263 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003264
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003265 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3266 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003267
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003268 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003269 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003270 /* Erik had a check here that the file descriptor in question
3271 * is legit; I postpone that to "run time"
3272 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003273 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3274 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003275 } else {
3276 /* Set ctx->pending_redirect, so we know what to do at the
3277 * end of the next parsed word. */
3278 ctx->pending_redirect = redir;
3279 }
3280 return 0;
3281}
3282
Eric Andersen25f27032001-04-26 23:22:31 +00003283/* If a redirect is immediately preceded by a number, that number is
3284 * supposed to tell which file descriptor to redirect. This routine
3285 * looks for such preceding numbers. In an ideal world this routine
3286 * needs to handle all the following classes of redirects...
3287 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3288 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3289 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3290 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003291 *
3292 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3293 * "2.7 Redirection
3294 * ... If n is quoted, the number shall not be recognized as part of
3295 * the redirection expression. For example:
3296 * echo \2>a
3297 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003298 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003299 *
3300 * A -1 return means no valid number was found,
3301 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003302 */
3303static int redirect_opt_num(o_string *o)
3304{
3305 int num;
3306
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003307 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003308 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003309 num = bb_strtou(o->data, NULL, 10);
3310 if (errno || num < 0)
3311 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003312 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003313 return num;
3314}
3315
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003316#if BB_MMU
3317#define fetch_till_str(as_string, input, word, skip_tabs) \
3318 fetch_till_str(input, word, skip_tabs)
3319#endif
3320static char *fetch_till_str(o_string *as_string,
3321 struct in_str *input,
3322 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003323 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003324{
3325 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003326 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003327 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003328 int ch;
3329
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003330 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003331 while (1) {
3332 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003333 if (ch != EOF)
3334 nommu_addchr(as_string, ch);
3335 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003336 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3337 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003338 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3339 heredoc.data[past_EOL] = '\0';
3340 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3341 return heredoc.data;
3342 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003343 while (ch == '\n') {
3344 o_addchr(&heredoc, ch);
3345 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003346 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003347 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003348 do {
3349 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003350 if (ch != EOF)
3351 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003352 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003353 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003354 }
3355 if (ch == EOF) {
3356 o_free_unsafe(&heredoc);
3357 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003358 }
3359 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003360 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003361 if (prev == '\\' && ch == '\\')
3362 /* Correctly handle foo\\<eol> (not a line cont.) */
3363 prev = 0; /* not \ */
3364 else
3365 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003366 }
3367}
3368
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003369/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3370 * and load them all. There should be exactly heredoc_cnt of them.
3371 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003372static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3373{
3374 struct pipe *pi = ctx->list_head;
3375
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003376 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003377 int i;
3378 struct command *cmd = pi->cmds;
3379
3380 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3381 pi->num_cmds,
3382 cmd->argv ? cmd->argv[0] : "NONE");
3383 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003384 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003385
3386 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3387 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003388 while (redir) {
3389 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003390 char *p;
3391
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003392 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003393 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003394 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003395 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003396 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003397 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003398 return 1;
3399 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003400 free(redir->rd_filename);
3401 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003402 heredoc_cnt--;
3403 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003404 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003405 }
3406 cmd++;
3407 }
3408 pi = pi->next;
3409 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003410#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003411 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003412 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003413 bb_error_msg_and_die("heredoc BUG 2");
3414#endif
3415 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003416}
3417
3418
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003419static int run_list(struct pipe *pi);
3420#if BB_MMU
3421#define parse_stream(pstring, input, end_trigger) \
3422 parse_stream(input, end_trigger)
3423#endif
3424static struct pipe *parse_stream(char **pstring,
3425 struct in_str *input,
3426 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003427
Eric Andersen25f27032001-04-26 23:22:31 +00003428
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003429#if !ENABLE_HUSH_FUNCTIONS
3430#define parse_group(dest, ctx, input, ch) \
3431 parse_group(ctx, input, ch)
3432#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003433static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003434 struct in_str *input, int ch)
3435{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003436 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003437 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003438 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003439 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003440 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003441 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003442
3443 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003444#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003445 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003446 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003447 if (done_word(dest, ctx))
3448 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003449 if (!command->argv)
3450 goto skip; /* (... */
3451 if (command->argv[1]) { /* word word ... (... */
3452 syntax_error_unexpected_ch('(');
3453 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003454 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003455 /* it is "word(..." or "word (..." */
3456 do
3457 ch = i_getch(input);
3458 while (ch == ' ' || ch == '\t');
3459 if (ch != ')') {
3460 syntax_error_unexpected_ch(ch);
3461 return 1;
3462 }
3463 nommu_addchr(&ctx->as_string, ch);
3464 do
3465 ch = i_getch(input);
3466 while (ch == ' ' || ch == '\t' || ch == '\n');
3467 if (ch != '{') {
3468 syntax_error_unexpected_ch(ch);
3469 return 1;
3470 }
3471 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003472 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003473 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003474 }
3475#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003476
3477#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003478 if (command->argv /* word [word]{... */
3479 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003480 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003481 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003482 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003483 debug_printf_parse("parse_group return 1: "
3484 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003485 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003486 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003487#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003488
3489#if ENABLE_HUSH_FUNCTIONS
3490 skip:
3491#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003492 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003493 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003494 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003495 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003496 } else {
3497 /* bash does not allow "{echo...", requires whitespace */
3498 ch = i_getch(input);
3499 if (ch != ' ' && ch != '\t' && ch != '\n') {
3500 syntax_error_unexpected_ch(ch);
3501 return 1;
3502 }
3503 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003504 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003505
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003506 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003507#if BB_MMU
3508# define as_string NULL
3509#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003510 char *as_string = NULL;
3511#endif
3512 pipe_list = parse_stream(&as_string, input, endch);
3513#if !BB_MMU
3514 if (as_string)
3515 o_addstr(&ctx->as_string, as_string);
3516#endif
3517 /* empty ()/{} or parse error? */
3518 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003519 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003520 if (!BB_MMU)
3521 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003522 debug_printf_parse("parse_group return 1: "
3523 "parse_stream returned %p\n", pipe_list);
3524 return 1;
3525 }
3526 command->group = pipe_list;
3527#if !BB_MMU
3528 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3529 command->group_as_string = as_string;
3530 debug_printf_parse("end of group, remembering as:'%s'\n",
3531 command->group_as_string);
3532#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003533#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003534 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003535 debug_printf_parse("parse_group return 0\n");
3536 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003537 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003538}
3539
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003540#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003541/* Subroutines for copying $(...) and `...` things */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003542static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003543/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003544static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003545{
3546 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003547 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003548 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003549 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003550 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003551 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003552 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003553 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003554 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003555 }
3556}
3557/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003558static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003559{
3560 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003561 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003562 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003563 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003564 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003565 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003566 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003567 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003568 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003569 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003570 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003571 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003572 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003573 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003574 add_till_backquote(dest, input, /*in_dquote:*/ 1);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003575 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003576 continue;
3577 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003578 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003579 }
3580}
3581/* Process `cmd` - copy contents until "`" is seen. Complicated by
3582 * \` quoting.
3583 * "Within the backquoted style of command substitution, backslash
3584 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3585 * The search for the matching backquote shall be satisfied by the first
3586 * backquote found without a preceding backslash; during this search,
3587 * if a non-escaped backquote is encountered within a shell comment,
3588 * a here-document, an embedded command substitution of the $(command)
3589 * form, or a quoted string, undefined results occur. A single-quoted
3590 * or double-quoted string that begins, but does not end, within the
3591 * "`...`" sequence produces undefined results."
3592 * Example Output
3593 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3594 */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003595static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003596{
3597 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003598 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003599 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003600 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003601 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003602 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3603 ch = i_getch(input);
3604 if (ch != '`'
3605 && ch != '$'
3606 && ch != '\\'
3607 && (!in_dquote || ch != '"')
3608 ) {
3609 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003610 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003611 }
3612 if (ch == EOF) {
3613 syntax_error_unterm_ch('`');
3614 /*xfunc_die(); - redundant */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003615 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003616 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003617 }
3618}
3619/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3620 * quoting and nested ()s.
3621 * "With the $(command) style of command substitution, all characters
3622 * following the open parenthesis to the matching closing parenthesis
3623 * constitute the command. Any valid shell script can be used for command,
3624 * except a script consisting solely of redirections which produces
3625 * unspecified results."
3626 * Example Output
3627 * echo $(echo '(TEST)' BEST) (TEST) BEST
3628 * echo $(echo 'TEST)' BEST) TEST) BEST
3629 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003630 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003631 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003632 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003633 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3634 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003635 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003636#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003637static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003638{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003639 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003640 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003641# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003642 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003643# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003644 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3645
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003646 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003647 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003648 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003649 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003650 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003651 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003652 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003653 if (!dbl)
3654 break;
3655 /* we look for closing )) of $((EXPR)) */
3656 if (i_peek(input) == end_ch) {
3657 i_getch(input); /* eat second ')' */
3658 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003659 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003660 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003661 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003662 if (ch == '(' || ch == '{') {
3663 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003664 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003665 o_addchr(dest, ch);
3666 continue;
3667 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003668 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003669 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003670 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003671 continue;
3672 }
3673 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003674 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003675 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003676 continue;
3677 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003678 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003679 add_till_backquote(dest, input, /*in_dquote:*/ 0);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003680 o_addchr(dest, ch);
3681 continue;
3682 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003683 if (ch == '\\') {
3684 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003685 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003686 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003687 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003688 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003689 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003690 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003691 continue;
3692 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003693 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003694 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003695}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003696#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003697
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003698/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003699#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003700#define parse_dollar(as_string, dest, input, quote_mask) \
3701 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003702#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003703#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003704static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003705 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003706 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003707{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003708 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003709
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003710 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003711 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003712 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003713 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003714 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003715 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003716 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003717 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003718 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003719 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003720 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003721 if (!isalnum(ch) && ch != '_')
3722 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003723 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003724 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003725 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003727 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003728 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003729 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003730 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003731 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003732 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003733 o_addchr(dest, ch | quote_mask);
3734 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003735 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003736 case '$': /* pid */
3737 case '!': /* last bg pid */
3738 case '?': /* last exit code */
3739 case '#': /* number of args */
3740 case '*': /* args */
3741 case '@': /* args */
3742 goto make_one_char_var;
3743 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003744 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3745
Denys Vlasenko74369502010-05-21 19:52:01 +02003746 ch = i_getch(input); /* eat '{' */
3747 nommu_addchr(as_string, ch);
3748
3749 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003750 /* It should be ${?}, or ${#var},
3751 * or even ${?+subst} - operator acting on a special variable,
3752 * or the beginning of variable name.
3753 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003754 if (ch == EOF
3755 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3756 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003757 bad_dollar_syntax:
3758 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003759 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003760 return 1;
3761 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003762 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003763 ch |= quote_mask;
3764
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003765 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003766 * However, this regresses some of our testsuite cases
3767 * which check invalid constructs like ${%}.
3768 * Oh well... let's check that the var name part is fine... */
3769
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003770 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003771 unsigned pos;
3772
Denys Vlasenko74369502010-05-21 19:52:01 +02003773 o_addchr(dest, ch);
3774 debug_printf_parse(": '%c'\n", ch);
3775
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003776 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003777 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003778 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003779 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003780
Denys Vlasenko74369502010-05-21 19:52:01 +02003781 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003782 unsigned end_ch;
3783 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003784 /* handle parameter expansions
3785 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3786 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003787 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003788 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003789
3790 /* Eat everything until closing '}' (or ':') */
3791 end_ch = '}';
3792 if (ENABLE_HUSH_BASH_COMPAT
3793 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003794 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003795 ) {
3796 /* It's ${var:N[:M]} thing */
3797 end_ch = '}' * 0x100 + ':';
3798 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003799 if (ENABLE_HUSH_BASH_COMPAT
3800 && ch == '/'
3801 ) {
3802 /* It's ${var/[/]pattern[/repl]} thing */
3803 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3804 i_getch(input);
3805 nommu_addchr(as_string, '/');
3806 ch = '\\';
3807 }
3808 end_ch = '}' * 0x100 + '/';
3809 }
3810 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003811 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003812 if (!BB_MMU)
3813 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003814#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003815 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003816#else
3817#error Simple code to only allow ${var} is not implemented
3818#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003819 if (as_string) {
3820 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003821 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003822 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003823
3824 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3825 /* close the first block: */
3826 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003827 /* while parsing N from ${var:N[:M]}
3828 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003829 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003830 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003831 end_ch = '}';
3832 goto again;
3833 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003834 /* got '}' */
3835 if (end_ch == '}' * 0x100 + ':') {
3836 /* it's ${var:N} - emulate :999999999 */
3837 o_addstr(dest, "999999999");
3838 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003839 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003840 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003841 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003842 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003843 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3844 break;
3845 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003846#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003847 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003848 unsigned pos;
3849
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003850 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003851 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003852# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003853 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003854 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003855 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003856 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3857 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003858 if (!BB_MMU)
3859 pos = dest->length;
3860 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003861 if (as_string) {
3862 o_addstr(as_string, dest->data + pos);
3863 o_addchr(as_string, ')');
3864 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003865 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003866 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003867 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003868 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003869# endif
3870# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003871 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3872 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003873 if (!BB_MMU)
3874 pos = dest->length;
3875 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003876 if (as_string) {
3877 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003878 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003879 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003880 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003881# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003882 break;
3883 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003884#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003885 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003886 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003887 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003888 ch = i_peek(input);
3889 if (isalnum(ch)) { /* it's $_name or $_123 */
3890 ch = '_';
3891 goto make_var;
3892 }
3893 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003894 /* TODO: $_ and $-: */
3895 /* $_ Shell or shell script name; or last argument of last command
3896 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3897 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003898 /* $- Option flags set by set builtin or shell options (-i etc) */
3899 default:
3900 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003901 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003902 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003903 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003904#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003905}
3906
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003907#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003908# if ENABLE_HUSH_BASH_COMPAT
3909#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3910 encode_string(dest, input, dquote_end, process_bkslash)
3911# else
3912/* only ${var/pattern/repl} (its pattern part) needs additional mode */
3913#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3914 encode_string(dest, input, dquote_end)
3915# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003916#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003917
3918#else /* !MMU */
3919
3920# if ENABLE_HUSH_BASH_COMPAT
3921/* all parameters are needed, no macro tricks */
3922# else
3923#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3924 encode_string(as_string, dest, input, dquote_end)
3925# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003926#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003927static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003928 o_string *dest,
3929 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02003930 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003931 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003932{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003933#if !ENABLE_HUSH_BASH_COMPAT
3934 const int process_bkslash = 1;
3935#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003936 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003937 int next;
3938
3939 again:
3940 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003941 if (ch != EOF)
3942 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003943 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003944 debug_printf_parse("encode_string return 0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003945 return 0;
3946 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003947 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003948 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003949 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003950 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003951 }
3952 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003953 if (ch != '\n') {
3954 next = i_peek(input);
3955 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003956 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003957 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003958 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003959 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003960 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003961 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003962 }
3963 /* bash:
3964 * "The backslash retains its special meaning [in "..."]
3965 * only when followed by one of the following characters:
3966 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003967 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003968 * NB: in (unquoted) heredoc, above does not apply to ",
3969 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003970 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003971 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003972 ch = i_getch(input); /* eat next */
3973 if (ch == '\n')
3974 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02003975 } /* else: ch remains == '\\', and we double it below: */
3976 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003977 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003978 goto again;
3979 }
3980 if (ch == '$') {
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003981 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003982 debug_printf_parse("encode_string return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003983 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003984 return 1;
3985 }
3986 goto again;
3987 }
3988#if ENABLE_HUSH_TICK
3989 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003990 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003991 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3992 o_addchr(dest, 0x80 | '`');
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003993 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003994 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3995 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003996 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003997 }
3998#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003999 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004000 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004001#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004002}
4003
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004004/*
4005 * Scan input until EOF or end_trigger char.
4006 * Return a list of pipes to execute, or NULL on EOF
4007 * or if end_trigger character is met.
4008 * On syntax error, exit is shell is not interactive,
4009 * reset parsing machinery and start parsing anew,
4010 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004011 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004012static struct pipe *parse_stream(char **pstring,
4013 struct in_str *input,
4014 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004015{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004016 struct parse_context ctx;
4017 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004018 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004019
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004020 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004021 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004022 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004023 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004024 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004025 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004026
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004027 /* If very first arg is "" or '', dest.data may end up NULL.
4028 * Preventing this: */
4029 o_addchr(&dest, '\0');
4030 dest.length = 0;
4031
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004032 /* We used to separate words on $IFS here. This was wrong.
4033 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004034 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004035 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004036
4037 reset: /* we come back here only on syntax errors in interactive shell */
4038
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004039 if (MAYBE_ASSIGNMENT != 0)
4040 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004041 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004042 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004043 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004044 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004045 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004046 int ch;
4047 int next;
4048 int redir_fd;
4049 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004050
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004051 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004052 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004053 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004054 if (ch == EOF) {
4055 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004056
4057 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004058 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004059 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004060 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004061 /* end_trigger == '}' case errors out earlier,
4062 * checking only ')' */
4063 if (end_trigger == ')') {
4064 syntax_error_unterm_ch('('); /* exits */
4065 /* goto parse_error; */
4066 }
4067
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004068 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004069 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004070 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004071 o_free(&dest);
4072 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004073 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004074 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004075 /* (this makes bare "&" cmd a no-op.
4076 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004077 if (pi->num_cmds == 0
4078 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4079 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004080 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004081 pi = NULL;
4082 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004083#if !BB_MMU
4084 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4085 if (pstring)
4086 *pstring = ctx.as_string.data;
4087 else
4088 o_free_unsafe(&ctx.as_string);
4089#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004090 debug_leave();
4091 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004092 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004093 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004094 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004095
4096 next = '\0';
4097 if (ch != '\n')
4098 next = i_peek(input);
4099
4100 is_special = "{}<>;&|()#'" /* special outside of "str" */
4101 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4102 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004103 if (ctx.command->argv /* word [word]{... - non-special */
4104 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004105 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004106 || (next != ';' /* }; - special */
4107 && next != ')' /* }) - special */
4108 && next != '&' /* }& and }&& ... - special */
4109 && next != '|' /* }|| ... - special */
4110 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004111 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004112 ) {
4113 /* They are not special, skip "{}" */
4114 is_special += 2;
4115 }
4116 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004117 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004118
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004119 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004120 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004121 o_addQchr(&dest, ch);
4122 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4123 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004124 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004125 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004126 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004127 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004128 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004129 continue;
4130 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004131
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004132 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004133 if (done_word(&dest, &ctx)) {
4134 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004135 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004136 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004137 /* Is this a case when newline is simply ignored?
4138 * Some examples:
4139 * "cmd | <newline> cmd ..."
4140 * "case ... in <newline> word) ..."
4141 */
4142 if (IS_NULL_CMD(ctx.command)
4143 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004144 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004145 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004146 * Without check #1, interactive shell
4147 * ignores even bare <newline>,
4148 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004149 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004150 * ps2> _ <=== wrong, should be ps1
4151 * Without check #2, "cmd & <newline>"
4152 * is similarly mistreated.
4153 * (BTW, this makes "cmd & cmd"
4154 * and "cmd && cmd" non-orthogonal.
4155 * Really, ask yourself, why
4156 * "cmd && <newline>" doesn't start
4157 * cmd but waits for more input?
4158 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004159 */
4160 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004161 if (pi->num_cmds != 0 /* check #1 */
4162 && pi->followup != PIPE_BG /* check #2 */
4163 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004164 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004165 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004166 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004167 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004168 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004169 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4170 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004171 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004172 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004173 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004174 heredoc_cnt = 0;
4175 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004176 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004177 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004178 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004179 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004180 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004181 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004182
4183 /* "cmd}" or "cmd }..." without semicolon or &:
4184 * } is an ordinary char in this case, even inside { cmd; }
4185 * Pathological example: { ""}; } should exec "}" cmd
4186 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004187 if (ch == '}') {
4188 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4189 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004190 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004191 ) {
4192 goto ordinary_char;
4193 }
4194 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4195 goto skip_end_trigger;
4196 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004197 }
4198
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004199 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004200 && (ch != ';' || heredoc_cnt == 0)
4201#if ENABLE_HUSH_CASE
4202 && (ch != ')'
4203 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004204 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004205 )
4206#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004207 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004208 if (heredoc_cnt) {
4209 /* This is technically valid:
4210 * { cat <<HERE; }; echo Ok
4211 * heredoc
4212 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004213 * HERE
4214 * but we don't support this.
4215 * We require heredoc to be in enclosing {}/(),
4216 * if any.
4217 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004218 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004219 goto parse_error;
4220 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004221 if (done_word(&dest, &ctx)) {
4222 goto parse_error;
4223 }
4224 done_pipe(&ctx, PIPE_SEQ);
4225 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004226 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004227 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004228 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004229 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004230 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004231#if !BB_MMU
4232 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4233 if (pstring)
4234 *pstring = ctx.as_string.data;
4235 else
4236 o_free_unsafe(&ctx.as_string);
4237#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004238 debug_leave();
4239 debug_printf_parse("parse_stream return %p: "
4240 "end_trigger char found\n",
4241 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004242 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004243 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004244 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004245 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004246 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004247 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004248
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004249 /* Catch <, > before deciding whether this word is
4250 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4251 switch (ch) {
4252 case '>':
4253 redir_fd = redirect_opt_num(&dest);
4254 if (done_word(&dest, &ctx)) {
4255 goto parse_error;
4256 }
4257 redir_style = REDIRECT_OVERWRITE;
4258 if (next == '>') {
4259 redir_style = REDIRECT_APPEND;
4260 ch = i_getch(input);
4261 nommu_addchr(&ctx.as_string, ch);
4262 }
4263#if 0
4264 else if (next == '(') {
4265 syntax_error(">(process) not supported");
4266 goto parse_error;
4267 }
4268#endif
4269 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4270 goto parse_error;
4271 continue; /* back to top of while (1) */
4272 case '<':
4273 redir_fd = redirect_opt_num(&dest);
4274 if (done_word(&dest, &ctx)) {
4275 goto parse_error;
4276 }
4277 redir_style = REDIRECT_INPUT;
4278 if (next == '<') {
4279 redir_style = REDIRECT_HEREDOC;
4280 heredoc_cnt++;
4281 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4282 ch = i_getch(input);
4283 nommu_addchr(&ctx.as_string, ch);
4284 } else if (next == '>') {
4285 redir_style = REDIRECT_IO;
4286 ch = i_getch(input);
4287 nommu_addchr(&ctx.as_string, ch);
4288 }
4289#if 0
4290 else if (next == '(') {
4291 syntax_error("<(process) not supported");
4292 goto parse_error;
4293 }
4294#endif
4295 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4296 goto parse_error;
4297 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004298 case '#':
4299 if (dest.length == 0 && !dest.has_quoted_part) {
4300 /* skip "#comment" */
4301 while (1) {
4302 ch = i_peek(input);
4303 if (ch == EOF || ch == '\n')
4304 break;
4305 i_getch(input);
4306 /* note: we do not add it to &ctx.as_string */
4307 }
4308 nommu_addchr(&ctx.as_string, '\n');
4309 continue; /* back to top of while (1) */
4310 }
4311 break;
4312 case '\\':
4313 if (next == '\n') {
4314 /* It's "\<newline>" */
4315#if !BB_MMU
4316 /* Remove trailing '\' from ctx.as_string */
4317 ctx.as_string.data[--ctx.as_string.length] = '\0';
4318#endif
4319 ch = i_getch(input); /* eat it */
4320 continue; /* back to top of while (1) */
4321 }
4322 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004323 }
4324
4325 if (dest.o_assignment == MAYBE_ASSIGNMENT
4326 /* check that we are not in word in "a=1 2>word b=1": */
4327 && !ctx.pending_redirect
4328 ) {
4329 /* ch is a special char and thus this word
4330 * cannot be an assignment */
4331 dest.o_assignment = NOT_ASSIGNMENT;
4332 }
4333
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004334 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4335
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004336 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004337 case '#': /* non-comment #: "echo a#b" etc */
4338 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004339 break;
4340 case '\\':
4341 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004342 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004343 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004344 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004345 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004346 /* note: ch != '\n' (that case does not reach this place) */
4347 o_addchr(&dest, '\\');
4348 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4349 o_addchr(&dest, ch);
4350 nommu_addchr(&ctx.as_string, ch);
4351 /* Example: echo Hello \2>file
4352 * we need to know that word 2 is quoted */
4353 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004354 break;
4355 case '$':
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004356 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004357 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004358 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004359 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004360 }
Eric Andersen25f27032001-04-26 23:22:31 +00004361 break;
4362 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004363 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004364 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004365 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004366 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004367 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004368 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004369 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004370 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004371 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004372 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004373 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004374 }
Eric Andersen25f27032001-04-26 23:22:31 +00004375 break;
4376 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004377 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004378 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004379 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004380 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004381 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004382 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004383 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004384#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004385 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004386 unsigned pos;
4387
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004388 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4389 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004390 pos = dest.length;
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004391 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004392# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004393 o_addstr(&ctx.as_string, dest.data + pos);
4394 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004395# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004396 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4397 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004398 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004399 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004400#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004401 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004402#if ENABLE_HUSH_CASE
4403 case_semi:
4404#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004405 if (done_word(&dest, &ctx)) {
4406 goto parse_error;
4407 }
4408 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004409#if ENABLE_HUSH_CASE
4410 /* Eat multiple semicolons, detect
4411 * whether it means something special */
4412 while (1) {
4413 ch = i_peek(input);
4414 if (ch != ';')
4415 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004416 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004417 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004418 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004419 ctx.ctx_dsemicolon = 1;
4420 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004421 break;
4422 }
4423 }
4424#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004425 new_cmd:
4426 /* We just finished a cmd. New one may start
4427 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004428 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004429 break;
4430 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004431 if (done_word(&dest, &ctx)) {
4432 goto parse_error;
4433 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004434 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004435 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004436 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004437 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004438 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004439 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004440 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004441 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004442 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004443 if (done_word(&dest, &ctx)) {
4444 goto parse_error;
4445 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004446#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004447 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004448 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004449#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004450 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004451 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004452 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004453 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004454 } else {
4455 /* we could pick up a file descriptor choice here
4456 * with redirect_opt_num(), but bash doesn't do it.
4457 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004458 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004459#if !BB_MMU
4460 o_reset_to_empty_unquoted(&ctx.as_string);
4461#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004462 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004463 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004464 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004465#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004466 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004467 if (ctx.ctx_res_w == RES_MATCH
4468 && ctx.command->argv == NULL /* not (word|(... */
4469 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004470 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004471 ) {
4472 continue;
4473 }
4474#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004475 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004476 if (parse_group(&dest, &ctx, input, ch) != 0) {
4477 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004478 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004479 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004480 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004481#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004482 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004483 goto case_semi;
4484#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004485 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004486 /* proper use of this character is caught by end_trigger:
4487 * if we see {, we call parse_group(..., end_trigger='}')
4488 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004489 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004490 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004491 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004492 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004493 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004494 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004495 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004496
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004497 parse_error:
4498 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004499 struct parse_context *pctx;
4500 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004501
4502 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004503 * Sample for finding leaks on syntax error recovery path.
4504 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004505 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004506 * Samples to catch leaks at execution:
4507 * while if (true | {true;}); then echo ok; fi; do break; done
4508 * 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 +00004509 */
4510 pctx = &ctx;
4511 do {
4512 /* Update pipe/command counts,
4513 * otherwise freeing may miss some */
4514 done_pipe(pctx, PIPE_SEQ);
4515 debug_printf_clean("freeing list %p from ctx %p\n",
4516 pctx->list_head, pctx);
4517 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004518 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004519 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004520#if !BB_MMU
4521 o_free_unsafe(&pctx->as_string);
4522#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004523 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004524 if (pctx != &ctx) {
4525 free(pctx);
4526 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004527 IF_HAS_KEYWORDS(pctx = p2;)
4528 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004529 /* Free text, clear all dest fields */
4530 o_free(&dest);
4531 /* If we are not in top-level parse, we return,
4532 * our caller will propagate error.
4533 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004534 if (end_trigger != ';') {
4535#if !BB_MMU
4536 if (pstring)
4537 *pstring = NULL;
4538#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004539 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004540 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004541 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004542 /* Discard cached input, force prompt */
4543 input->p = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004544 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004545 }
Eric Andersen25f27032001-04-26 23:22:31 +00004546}
4547
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004548
4549/*** Execution routines ***/
4550
4551/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004552#if !ENABLE_HUSH_BASH_COMPAT
4553/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4554#define expand_string_to_string(str, do_unbackslash) \
4555 expand_string_to_string(str)
4556#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004557static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004558#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004559static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004560#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004561
4562/* expand_strvec_to_strvec() takes a list of strings, expands
4563 * all variable references within and returns a pointer to
4564 * a list of expanded strings, possibly with larger number
4565 * of strings. (Think VAR="a b"; echo $VAR).
4566 * This new list is allocated as a single malloc block.
4567 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004568 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004569 * Caller can deallocate entire list by single free(list). */
4570
Denys Vlasenko238081f2010-10-03 14:26:26 +02004571/* A horde of its helpers come first: */
4572
4573static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4574{
4575 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004576 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004577
Denys Vlasenko9e800222010-10-03 14:28:04 +02004578#if ENABLE_HUSH_BRACE_EXPANSION
4579 if (c == '{' || c == '}') {
4580 /* { -> \{, } -> \} */
4581 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004582 /* And now we want to add { or } and continue:
4583 * o_addchr(o, c);
4584 * continue;
4585 * luckily, just falling throught achieves this.
4586 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004587 }
4588#endif
4589 o_addchr(o, c);
4590 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004591 /* \z -> \\\z; \<eol> -> \\<eol> */
4592 o_addchr(o, '\\');
4593 if (len) {
4594 len--;
4595 o_addchr(o, '\\');
4596 o_addchr(o, *str++);
4597 }
4598 }
4599 }
4600}
4601
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004602/* Store given string, finalizing the word and starting new one whenever
4603 * we encounter IFS char(s). This is used for expanding variable values.
4604 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4605static int expand_on_ifs(o_string *output, int n, const char *str)
4606{
4607 while (1) {
4608 int word_len = strcspn(str, G.ifs);
4609 if (word_len) {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004610 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004611 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004612 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004613 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004614 * Example: "v='\*'; echo b$v" prints "b\*"
4615 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004616 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004617 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004618 /*/ Why can't we do it easier? */
4619 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4620 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4621 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004622 str += word_len;
4623 }
4624 if (!*str) /* EOL - do not finalize word */
4625 break;
4626 o_addchr(output, '\0');
4627 debug_print_list("expand_on_ifs", output, n);
4628 n = o_save_ptr(output, n);
4629 str += strspn(str, G.ifs); /* skip ifs chars */
4630 }
4631 debug_print_list("expand_on_ifs[1]", output, n);
4632 return n;
4633}
4634
4635/* Helper to expand $((...)) and heredoc body. These act as if
4636 * they are in double quotes, with the exception that they are not :).
4637 * Just the rules are similar: "expand only $var and `cmd`"
4638 *
4639 * Returns malloced string.
4640 * As an optimization, we return NULL if expansion is not needed.
4641 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004642#if !ENABLE_HUSH_BASH_COMPAT
4643/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4644#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4645 encode_then_expand_string(str)
4646#endif
4647static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004648{
4649 char *exp_str;
4650 struct in_str input;
4651 o_string dest = NULL_O_STRING;
4652
4653 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004654 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004655#if ENABLE_HUSH_TICK
4656 && !strchr(str, '`')
4657#endif
4658 ) {
4659 return NULL;
4660 }
4661
4662 /* We need to expand. Example:
4663 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4664 */
4665 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004666 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004667 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004668 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004669 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4670 o_free_unsafe(&dest);
4671 return exp_str;
4672}
4673
4674#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004675static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004676{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004677 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004678 arith_t res;
4679 char *exp_str;
4680
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004681 math_state.lookupvar = get_local_var_value;
4682 math_state.setvar = set_local_var_from_halves;
4683 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004684 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004685 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004686 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004687 if (errmsg_p)
4688 *errmsg_p = math_state.errmsg;
4689 if (math_state.errmsg)
4690 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004691 return res;
4692}
4693#endif
4694
4695#if ENABLE_HUSH_BASH_COMPAT
4696/* ${var/[/]pattern[/repl]} helpers */
4697static char *strstr_pattern(char *val, const char *pattern, int *size)
4698{
4699 while (1) {
4700 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4701 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4702 if (end) {
4703 *size = end - val;
4704 return val;
4705 }
4706 if (*val == '\0')
4707 return NULL;
4708 /* Optimization: if "*pat" did not match the start of "string",
4709 * we know that "tring", "ring" etc will not match too:
4710 */
4711 if (pattern[0] == '*')
4712 return NULL;
4713 val++;
4714 }
4715}
4716static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4717{
4718 char *result = NULL;
4719 unsigned res_len = 0;
4720 unsigned repl_len = strlen(repl);
4721
4722 while (1) {
4723 int size;
4724 char *s = strstr_pattern(val, pattern, &size);
4725 if (!s)
4726 break;
4727
4728 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4729 memcpy(result + res_len, val, s - val);
4730 res_len += s - val;
4731 strcpy(result + res_len, repl);
4732 res_len += repl_len;
4733 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4734
4735 val = s + size;
4736 if (exp_op == '/')
4737 break;
4738 }
4739 if (val[0] && result) {
4740 result = xrealloc(result, res_len + strlen(val) + 1);
4741 strcpy(result + res_len, val);
4742 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4743 }
4744 debug_printf_varexp("result:'%s'\n", result);
4745 return result;
4746}
4747#endif
4748
4749/* Helper:
4750 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4751 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004752static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004753{
4754 const char *val = NULL;
4755 char *to_be_freed = NULL;
4756 char *p = *pp;
4757 char *var;
4758 char first_char;
4759 char exp_op;
4760 char exp_save = exp_save; /* for compiler */
4761 char *exp_saveptr; /* points to expansion operator */
4762 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004763 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004764
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004765 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004766 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004767 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004768 arg0 = arg[0];
4769 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004770 exp_op = 0;
4771
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004772 if (first_char == '#' /* ${#... */
4773 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4774 ) {
4775 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004776 var++;
4777 exp_op = 'L';
4778 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004779 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004780 if (exp_saveptr /* if 2nd char is one of expansion operators */
4781 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4782 ) {
4783 /* ${?:0}, ${#[:]%0} etc */
4784 exp_saveptr = var + 1;
4785 } else {
4786 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4787 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4788 }
4789 exp_op = exp_save = *exp_saveptr;
4790 if (exp_op) {
4791 exp_word = exp_saveptr + 1;
4792 if (exp_op == ':') {
4793 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004794//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004795 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004796 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004797 ) {
4798 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4799 exp_op = ':';
4800 exp_word--;
4801 }
4802 }
4803 *exp_saveptr = '\0';
4804 } /* else: it's not an expansion op, but bare ${var} */
4805 }
4806
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004807 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004808 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004809 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004810 int n = xatoi_positive(var);
4811 if (n < G.global_argc)
4812 val = G.global_argv[n];
4813 /* else val remains NULL: $N with too big N */
4814 } else {
4815 switch (var[0]) {
4816 case '$': /* pid */
4817 val = utoa(G.root_pid);
4818 break;
4819 case '!': /* bg pid */
4820 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4821 break;
4822 case '?': /* exitcode */
4823 val = utoa(G.last_exitcode);
4824 break;
4825 case '#': /* argc */
4826 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4827 break;
4828 default:
4829 val = get_local_var_value(var);
4830 }
4831 }
4832
4833 /* Handle any expansions */
4834 if (exp_op == 'L') {
4835 debug_printf_expand("expand: length(%s)=", val);
4836 val = utoa(val ? strlen(val) : 0);
4837 debug_printf_expand("%s\n", val);
4838 } else if (exp_op) {
4839 if (exp_op == '%' || exp_op == '#') {
4840 /* Standard-mandated substring removal ops:
4841 * ${parameter%word} - remove smallest suffix pattern
4842 * ${parameter%%word} - remove largest suffix pattern
4843 * ${parameter#word} - remove smallest prefix pattern
4844 * ${parameter##word} - remove largest prefix pattern
4845 *
4846 * Word is expanded to produce a glob pattern.
4847 * Then var's value is matched to it and matching part removed.
4848 */
4849 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004850 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004851 char *exp_exp_word;
4852 char *loc;
4853 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02004854 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004855 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004856 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004857 if (exp_exp_word)
4858 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004859 /* HACK ALERT. We depend here on the fact that
4860 * G.global_argv and results of utoa and get_local_var_value
4861 * are actually in writable memory:
4862 * scan_and_match momentarily stores NULs there. */
4863 t = (char*)val;
4864 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004865 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004866 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004867 free(exp_exp_word);
4868 if (loc) { /* match was found */
4869 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004870 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004871 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004872 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004873 }
4874 }
4875 }
4876#if ENABLE_HUSH_BASH_COMPAT
4877 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004878 /* It's ${var/[/]pattern[/repl]} thing.
4879 * Note that in encoded form it has TWO parts:
4880 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02004881 * and if // is used, it is encoded as \:
4882 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004883 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004884 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004885 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004886 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004887 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004888 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004889 * by the usual expansion rules:
4890 * >az; >bz;
4891 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4892 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4893 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4894 * v='a bz'; echo ${v/a*z/\z} prints "z"
4895 * (note that a*z _pattern_ is never globbed!)
4896 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004897 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004898 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004899 if (!pattern)
4900 pattern = xstrdup(exp_word);
4901 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4902 *p++ = SPECIAL_VAR_SYMBOL;
4903 exp_word = p;
4904 p = strchr(p, SPECIAL_VAR_SYMBOL);
4905 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004906 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004907 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4908 /* HACK ALERT. We depend here on the fact that
4909 * G.global_argv and results of utoa and get_local_var_value
4910 * are actually in writable memory:
4911 * replace_pattern momentarily stores NULs there. */
4912 t = (char*)val;
4913 to_be_freed = replace_pattern(t,
4914 pattern,
4915 (repl ? repl : exp_word),
4916 exp_op);
4917 if (to_be_freed) /* at least one replace happened */
4918 val = to_be_freed;
4919 free(pattern);
4920 free(repl);
4921 }
4922 }
4923#endif
4924 else if (exp_op == ':') {
4925#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4926 /* It's ${var:N[:M]} bashism.
4927 * Note that in encoded form it has TWO parts:
4928 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4929 */
4930 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02004931 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004932
Denys Vlasenko063847d2010-09-15 13:33:02 +02004933 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4934 if (errmsg)
4935 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004936 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4937 *p++ = SPECIAL_VAR_SYMBOL;
4938 exp_word = p;
4939 p = strchr(p, SPECIAL_VAR_SYMBOL);
4940 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02004941 len = expand_and_evaluate_arith(exp_word, &errmsg);
4942 if (errmsg)
4943 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004944 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004945 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004946 if (beg < 0) /* bash compat */
4947 beg = 0;
4948 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004949 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02004950 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02004951 val = NULL;
4952 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004953 /* Paranoia. What if user entered 9999999999999
4954 * which fits in arith_t but not int? */
4955 if (len >= INT_MAX)
4956 len = INT_MAX;
4957 val = to_be_freed = xstrndup(val + beg, len);
4958 }
4959 debug_printf_varexp("val:'%s'\n", val);
4960 } else
4961#endif
4962 {
4963 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004964 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004965 }
4966 } else { /* one of "-=+?" */
4967 /* Standard-mandated substitution ops:
4968 * ${var?word} - indicate error if unset
4969 * If var is unset, word (or a message indicating it is unset
4970 * if word is null) is written to standard error
4971 * and the shell exits with a non-zero exit status.
4972 * Otherwise, the value of var is substituted.
4973 * ${var-word} - use default value
4974 * If var is unset, word is substituted.
4975 * ${var=word} - assign and use default value
4976 * If var is unset, word is assigned to var.
4977 * In all cases, final value of var is substituted.
4978 * ${var+word} - use alternative value
4979 * If var is unset, null is substituted.
4980 * Otherwise, word is substituted.
4981 *
4982 * Word is subjected to tilde expansion, parameter expansion,
4983 * command substitution, and arithmetic expansion.
4984 * If word is not needed, it is not expanded.
4985 *
4986 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4987 * but also treat null var as if it is unset.
4988 */
4989 int use_word = (!val || ((exp_save == ':') && !val[0]));
4990 if (exp_op == '+')
4991 use_word = !use_word;
4992 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4993 (exp_save == ':') ? "true" : "false", use_word);
4994 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004995 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004996 if (to_be_freed)
4997 exp_word = to_be_freed;
4998 if (exp_op == '?') {
4999 /* mimic bash message */
5000 die_if_script("%s: %s",
5001 var,
5002 exp_word[0] ? exp_word : "parameter null or not set"
5003 );
5004//TODO: how interactive bash aborts expansion mid-command?
5005 } else {
5006 val = exp_word;
5007 }
5008
5009 if (exp_op == '=') {
5010 /* ${var=[word]} or ${var:=[word]} */
5011 if (isdigit(var[0]) || var[0] == '#') {
5012 /* mimic bash message */
5013 die_if_script("$%s: cannot assign in this way", var);
5014 val = NULL;
5015 } else {
5016 char *new_var = xasprintf("%s=%s", var, val);
5017 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5018 }
5019 }
5020 }
5021 } /* one of "-=+?" */
5022
5023 *exp_saveptr = exp_save;
5024 } /* if (exp_op) */
5025
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005026 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005027
5028 *pp = p;
5029 *to_be_freed_pp = to_be_freed;
5030 return val;
5031}
5032
5033/* Expand all variable references in given string, adding words to list[]
5034 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5035 * to be filled). This routine is extremely tricky: has to deal with
5036 * variables/parameters with whitespace, $* and $@, and constructs like
5037 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005038static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005039{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005040 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005041 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005042 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005043 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005044 char *p;
5045
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005046 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5047 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005048 debug_print_list("expand_vars_to_list", output, n);
5049 n = o_save_ptr(output, n);
5050 debug_print_list("expand_vars_to_list[0]", output, n);
5051
5052 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5053 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005054 char *to_be_freed = NULL;
5055 const char *val = NULL;
5056#if ENABLE_HUSH_TICK
5057 o_string subst_result = NULL_O_STRING;
5058#endif
5059#if ENABLE_SH_MATH_SUPPORT
5060 char arith_buf[sizeof(arith_t)*3 + 2];
5061#endif
5062 o_addblock(output, arg, p - arg);
5063 debug_print_list("expand_vars_to_list[1]", output, n);
5064 arg = ++p;
5065 p = strchr(p, SPECIAL_VAR_SYMBOL);
5066
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005067 /* Fetch special var name (if it is indeed one of them)
5068 * and quote bit, force the bit on if singleword expansion -
5069 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005070 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005071
5072 /* Is this variable quoted and thus expansion can't be null?
5073 * "$@" is special. Even if quoted, it can still
5074 * expand to nothing (not even an empty string),
5075 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005076 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005077 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005078
5079 switch (first_ch & 0x7f) {
5080 /* Highest bit in first_ch indicates that var is double-quoted */
5081 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005082 case '@': {
5083 int i;
5084 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005085 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005086 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005087 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005088 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005089 while (G.global_argv[i]) {
5090 n = expand_on_ifs(output, n, G.global_argv[i]);
5091 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5092 if (G.global_argv[i++][0] && G.global_argv[i]) {
5093 /* this argv[] is not empty and not last:
5094 * put terminating NUL, start new word */
5095 o_addchr(output, '\0');
5096 debug_print_list("expand_vars_to_list[2]", output, n);
5097 n = o_save_ptr(output, n);
5098 debug_print_list("expand_vars_to_list[3]", output, n);
5099 }
5100 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005101 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005102 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005103 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005104 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005105 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005106 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005107 while (1) {
5108 o_addQstr(output, G.global_argv[i]);
5109 if (++i >= G.global_argc)
5110 break;
5111 o_addchr(output, '\0');
5112 debug_print_list("expand_vars_to_list[4]", output, n);
5113 n = o_save_ptr(output, n);
5114 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005115 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005116 while (1) {
5117 o_addQstr(output, G.global_argv[i]);
5118 if (!G.global_argv[++i])
5119 break;
5120 if (G.ifs[0])
5121 o_addchr(output, G.ifs[0]);
5122 }
5123 }
5124 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005125 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005126 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5127 /* "Empty variable", used to make "" etc to not disappear */
5128 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005129 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005130 break;
5131#if ENABLE_HUSH_TICK
5132 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005133 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005134 arg++;
5135 /* Can't just stuff it into output o_string,
5136 * expanded result may need to be globbed
5137 * and $IFS-splitted */
5138 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5139 G.last_exitcode = process_command_subs(&subst_result, arg);
5140 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5141 val = subst_result.data;
5142 goto store_val;
5143#endif
5144#if ENABLE_SH_MATH_SUPPORT
5145 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5146 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005147
5148 arg++; /* skip '+' */
5149 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5150 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005151 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005152 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5153 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005154 val = arith_buf;
5155 break;
5156 }
5157#endif
5158 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005159 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005160 IF_HUSH_TICK(store_val:)
5161 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005162 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5163 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005164 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005165 n = expand_on_ifs(output, n, val);
5166 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005167 }
5168 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005169 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5170 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005171 }
5172 break;
5173
5174 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5175
5176 if (val && val[0]) {
5177 o_addQstr(output, val);
5178 }
5179 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005180
5181 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5182 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005183 if (*p != SPECIAL_VAR_SYMBOL)
5184 *p = SPECIAL_VAR_SYMBOL;
5185
5186#if ENABLE_HUSH_TICK
5187 o_free(&subst_result);
5188#endif
5189 arg = ++p;
5190 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5191
5192 if (arg[0]) {
5193 debug_print_list("expand_vars_to_list[a]", output, n);
5194 /* this part is literal, and it was already pre-quoted
5195 * if needed (much earlier), do not use o_addQstr here! */
5196 o_addstr_with_NUL(output, arg);
5197 debug_print_list("expand_vars_to_list[b]", output, n);
5198 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005199 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005200 ) {
5201 n--;
5202 /* allow to reuse list[n] later without re-growth */
5203 output->has_empty_slot = 1;
5204 } else {
5205 o_addchr(output, '\0');
5206 }
5207
5208 return n;
5209}
5210
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005211static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005212{
5213 int n;
5214 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005215 o_string output = NULL_O_STRING;
5216
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005217 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005218
5219 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005220 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005221 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005222 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005223 }
5224 debug_print_list("expand_variables", &output, n);
5225
5226 /* output.data (malloced in one block) gets returned in "list" */
5227 list = o_finalize_list(&output, n);
5228 debug_print_strings("expand_variables[1]", list);
5229 return list;
5230}
5231
5232static char **expand_strvec_to_strvec(char **argv)
5233{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005234 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005235}
5236
5237#if ENABLE_HUSH_BASH_COMPAT
5238static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5239{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005240 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005241}
5242#endif
5243
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005244/* Used for expansion of right hand of assignments,
5245 * $((...)), heredocs, variable espansion parts.
5246 *
5247 * NB: should NOT do globbing!
5248 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5249 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005250static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005251{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005252#if !ENABLE_HUSH_BASH_COMPAT
5253 const int do_unbackslash = 1;
5254#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005255 char *argv[2], **list;
5256
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005257 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005258 /* This is generally an optimization, but it also
5259 * handles "", which otherwise trips over !list[0] check below.
5260 * (is this ever happens that we actually get str="" here?)
5261 */
5262 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5263 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005264 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005265 return xstrdup(str);
5266 }
5267
5268 argv[0] = (char*)str;
5269 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005270 list = expand_variables(argv, do_unbackslash
5271 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5272 : EXP_FLAG_SINGLEWORD
5273 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005274 if (HUSH_DEBUG)
5275 if (!list[0] || list[1])
5276 bb_error_msg_and_die("BUG in varexp2");
5277 /* actually, just move string 2*sizeof(char*) bytes back */
5278 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005279 if (do_unbackslash)
5280 unbackslash((char*)list);
5281 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005282 return (char*)list;
5283}
5284
5285/* Used for "eval" builtin */
5286static char* expand_strvec_to_string(char **argv)
5287{
5288 char **list;
5289
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005290 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005291 /* Convert all NULs to spaces */
5292 if (list[0]) {
5293 int n = 1;
5294 while (list[n]) {
5295 if (HUSH_DEBUG)
5296 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5297 bb_error_msg_and_die("BUG in varexp3");
5298 /* bash uses ' ' regardless of $IFS contents */
5299 list[n][-1] = ' ';
5300 n++;
5301 }
5302 }
5303 overlapping_strcpy((char*)list, list[0]);
5304 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5305 return (char*)list;
5306}
5307
5308static char **expand_assignments(char **argv, int count)
5309{
5310 int i;
5311 char **p;
5312
5313 G.expanded_assignments = p = NULL;
5314 /* Expand assignments into one string each */
5315 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005316 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005317 }
5318 G.expanded_assignments = NULL;
5319 return p;
5320}
5321
5322
5323#if BB_MMU
5324/* never called */
5325void re_execute_shell(char ***to_free, const char *s,
5326 char *g_argv0, char **g_argv,
5327 char **builtin_argv) NORETURN;
5328
5329static void reset_traps_to_defaults(void)
5330{
5331 /* This function is always called in a child shell
5332 * after fork (not vfork, NOMMU doesn't use this function).
5333 */
5334 unsigned sig;
5335 unsigned mask;
5336
5337 /* Child shells are not interactive.
5338 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5339 * Testcase: (while :; do :; done) + ^Z should background.
5340 * Same goes for SIGTERM, SIGHUP, SIGINT.
5341 */
5342 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5343 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5344
5345 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5346 * Stupid. It can be done with *single* &= op, but we can't use
5347 * the fact that G.blocked_set is implemented as a bitmask
5348 * in libc... */
5349 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5350 sig = 1;
5351 while (1) {
5352 if (mask & 1) {
5353 /* Careful. Only if no trap or trap is not "" */
5354 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5355 sigdelset(&G.blocked_set, sig);
5356 }
5357 mask >>= 1;
5358 if (!mask)
5359 break;
5360 sig++;
5361 }
5362 /* Our homegrown sig mask is saner to work with :) */
5363 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5364
5365 /* Resetting all traps to default except empty ones */
5366 mask = G.non_DFL_mask;
5367 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5368 if (!G.traps[sig] || !G.traps[sig][0])
5369 continue;
5370 free(G.traps[sig]);
5371 G.traps[sig] = NULL;
5372 /* There is no signal for 0 (EXIT) */
5373 if (sig == 0)
5374 continue;
5375 /* There was a trap handler, we just removed it.
5376 * But if sig still has non-DFL handling,
5377 * we should not unblock the sig. */
5378 if (mask & 1)
5379 continue;
5380 sigdelset(&G.blocked_set, sig);
5381 }
5382 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5383}
5384
5385#else /* !BB_MMU */
5386
5387static void re_execute_shell(char ***to_free, const char *s,
5388 char *g_argv0, char **g_argv,
5389 char **builtin_argv) NORETURN;
5390static void re_execute_shell(char ***to_free, const char *s,
5391 char *g_argv0, char **g_argv,
5392 char **builtin_argv)
5393{
5394# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5395 /* delims + 2 * (number of bytes in printed hex numbers) */
5396 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5397 char *heredoc_argv[4];
5398 struct variable *cur;
5399# if ENABLE_HUSH_FUNCTIONS
5400 struct function *funcp;
5401# endif
5402 char **argv, **pp;
5403 unsigned cnt;
5404 unsigned long long empty_trap_mask;
5405
5406 if (!g_argv0) { /* heredoc */
5407 argv = heredoc_argv;
5408 argv[0] = (char *) G.argv0_for_re_execing;
5409 argv[1] = (char *) "-<";
5410 argv[2] = (char *) s;
5411 argv[3] = NULL;
5412 pp = &argv[3]; /* used as pointer to empty environment */
5413 goto do_exec;
5414 }
5415
5416 cnt = 0;
5417 pp = builtin_argv;
5418 if (pp) while (*pp++)
5419 cnt++;
5420
5421 empty_trap_mask = 0;
5422 if (G.traps) {
5423 int sig;
5424 for (sig = 1; sig < NSIG; sig++) {
5425 if (G.traps[sig] && !G.traps[sig][0])
5426 empty_trap_mask |= 1LL << sig;
5427 }
5428 }
5429
5430 sprintf(param_buf, NOMMU_HACK_FMT
5431 , (unsigned) G.root_pid
5432 , (unsigned) G.root_ppid
5433 , (unsigned) G.last_bg_pid
5434 , (unsigned) G.last_exitcode
5435 , cnt
5436 , empty_trap_mask
5437 IF_HUSH_LOOPS(, G.depth_of_loop)
5438 );
5439# undef NOMMU_HACK_FMT
5440 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5441 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5442 */
5443 cnt += 6;
5444 for (cur = G.top_var; cur; cur = cur->next) {
5445 if (!cur->flg_export || cur->flg_read_only)
5446 cnt += 2;
5447 }
5448# if ENABLE_HUSH_FUNCTIONS
5449 for (funcp = G.top_func; funcp; funcp = funcp->next)
5450 cnt += 3;
5451# endif
5452 pp = g_argv;
5453 while (*pp++)
5454 cnt++;
5455 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5456 *pp++ = (char *) G.argv0_for_re_execing;
5457 *pp++ = param_buf;
5458 for (cur = G.top_var; cur; cur = cur->next) {
5459 if (strcmp(cur->varstr, hush_version_str) == 0)
5460 continue;
5461 if (cur->flg_read_only) {
5462 *pp++ = (char *) "-R";
5463 *pp++ = cur->varstr;
5464 } else if (!cur->flg_export) {
5465 *pp++ = (char *) "-V";
5466 *pp++ = cur->varstr;
5467 }
5468 }
5469# if ENABLE_HUSH_FUNCTIONS
5470 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5471 *pp++ = (char *) "-F";
5472 *pp++ = funcp->name;
5473 *pp++ = funcp->body_as_string;
5474 }
5475# endif
5476 /* We can pass activated traps here. Say, -Tnn:trap_string
5477 *
5478 * However, POSIX says that subshells reset signals with traps
5479 * to SIG_DFL.
5480 * I tested bash-3.2 and it not only does that with true subshells
5481 * of the form ( list ), but with any forked children shells.
5482 * I set trap "echo W" WINCH; and then tried:
5483 *
5484 * { echo 1; sleep 20; echo 2; } &
5485 * while true; do echo 1; sleep 20; echo 2; break; done &
5486 * true | { echo 1; sleep 20; echo 2; } | cat
5487 *
5488 * In all these cases sending SIGWINCH to the child shell
5489 * did not run the trap. If I add trap "echo V" WINCH;
5490 * _inside_ group (just before echo 1), it works.
5491 *
5492 * I conclude it means we don't need to pass active traps here.
5493 * Even if we would use signal handlers instead of signal masking
5494 * in order to implement trap handling,
5495 * exec syscall below resets signals to SIG_DFL for us.
5496 */
5497 *pp++ = (char *) "-c";
5498 *pp++ = (char *) s;
5499 if (builtin_argv) {
5500 while (*++builtin_argv)
5501 *pp++ = *builtin_argv;
5502 *pp++ = (char *) "";
5503 }
5504 *pp++ = g_argv0;
5505 while (*g_argv)
5506 *pp++ = *g_argv++;
5507 /* *pp = NULL; - is already there */
5508 pp = environ;
5509
5510 do_exec:
5511 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5512 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5513 execve(bb_busybox_exec_path, argv, pp);
5514 /* Fallback. Useful for init=/bin/hush usage etc */
5515 if (argv[0][0] == '/')
5516 execve(argv[0], argv, pp);
5517 xfunc_error_retval = 127;
5518 bb_error_msg_and_die("can't re-execute the shell");
5519}
5520#endif /* !BB_MMU */
5521
5522
5523static int run_and_free_list(struct pipe *pi);
5524
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005525/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005526 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5527 * end_trigger controls how often we stop parsing
5528 * NUL: parse all, execute, return
5529 * ';': parse till ';' or newline, execute, repeat till EOF
5530 */
5531static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005532{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005533 /* Why we need empty flag?
5534 * An obscure corner case "false; ``; echo $?":
5535 * empty command in `` should still set $? to 0.
5536 * But we can't just set $? to 0 at the start,
5537 * this breaks "false; echo `echo $?`" case.
5538 */
5539 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005540 while (1) {
5541 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005542
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005543#if ENABLE_HUSH_INTERACTIVE
5544 if (end_trigger == ';')
5545 inp->promptmode = 0; /* PS1 */
5546#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005547 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005548 if (!pipe_list) { /* EOF */
5549 if (empty)
5550 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005551 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005552 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005553 debug_print_tree(pipe_list, 0);
5554 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5555 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005556 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005557 }
Eric Andersen25f27032001-04-26 23:22:31 +00005558}
5559
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005560static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005561{
5562 struct in_str input;
5563 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005564 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005565}
5566
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005567static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005568{
Eric Andersen25f27032001-04-26 23:22:31 +00005569 struct in_str input;
5570 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005571 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005572}
5573
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005574#if ENABLE_HUSH_TICK
5575static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5576{
5577 pid_t pid;
5578 int channel[2];
5579# if !BB_MMU
5580 char **to_free = NULL;
5581# endif
5582
5583 xpipe(channel);
5584 pid = BB_MMU ? xfork() : xvfork();
5585 if (pid == 0) { /* child */
5586 disable_restore_tty_pgrp_on_exit();
5587 /* Process substitution is not considered to be usual
5588 * 'command execution'.
5589 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5590 */
5591 bb_signals(0
5592 + (1 << SIGTSTP)
5593 + (1 << SIGTTIN)
5594 + (1 << SIGTTOU)
5595 , SIG_IGN);
5596 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5597 close(channel[0]); /* NB: close _first_, then move fd! */
5598 xmove_fd(channel[1], 1);
5599 /* Prevent it from trying to handle ctrl-z etc */
5600 IF_HUSH_JOB(G.run_list_level = 1;)
5601 /* Awful hack for `trap` or $(trap).
5602 *
5603 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5604 * contains an example where "trap" is executed in a subshell:
5605 *
5606 * save_traps=$(trap)
5607 * ...
5608 * eval "$save_traps"
5609 *
5610 * Standard does not say that "trap" in subshell shall print
5611 * parent shell's traps. It only says that its output
5612 * must have suitable form, but then, in the above example
5613 * (which is not supposed to be normative), it implies that.
5614 *
5615 * bash (and probably other shell) does implement it
5616 * (traps are reset to defaults, but "trap" still shows them),
5617 * but as a result, "trap" logic is hopelessly messed up:
5618 *
5619 * # trap
5620 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5621 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5622 * # true | trap <--- trap is in subshell - no output (ditto)
5623 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5624 * trap -- 'echo Ho' SIGWINCH
5625 * # echo `(trap)` <--- in subshell in subshell - output
5626 * trap -- 'echo Ho' SIGWINCH
5627 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5628 * trap -- 'echo Ho' SIGWINCH
5629 *
5630 * The rules when to forget and when to not forget traps
5631 * get really complex and nonsensical.
5632 *
5633 * Our solution: ONLY bare $(trap) or `trap` is special.
5634 */
5635 s = skip_whitespace(s);
5636 if (strncmp(s, "trap", 4) == 0
5637 && skip_whitespace(s + 4)[0] == '\0'
5638 ) {
5639 static const char *const argv[] = { NULL, NULL };
5640 builtin_trap((char**)argv);
5641 exit(0); /* not _exit() - we need to fflush */
5642 }
5643# if BB_MMU
5644 reset_traps_to_defaults();
5645 parse_and_run_string(s);
5646 _exit(G.last_exitcode);
5647# else
5648 /* We re-execute after vfork on NOMMU. This makes this script safe:
5649 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5650 * huge=`cat BIG` # was blocking here forever
5651 * echo OK
5652 */
5653 re_execute_shell(&to_free,
5654 s,
5655 G.global_argv[0],
5656 G.global_argv + 1,
5657 NULL);
5658# endif
5659 }
5660
5661 /* parent */
5662 *pid_p = pid;
5663# if ENABLE_HUSH_FAST
5664 G.count_SIGCHLD++;
5665//bb_error_msg("[%d] fork in generate_stream_from_string:"
5666// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5667// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5668# endif
5669 enable_restore_tty_pgrp_on_exit();
5670# if !BB_MMU
5671 free(to_free);
5672# endif
5673 close(channel[1]);
5674 close_on_exec_on(channel[0]);
5675 return xfdopen_for_read(channel[0]);
5676}
5677
5678/* Return code is exit status of the process that is run. */
5679static int process_command_subs(o_string *dest, const char *s)
5680{
5681 FILE *fp;
5682 struct in_str pipe_str;
5683 pid_t pid;
5684 int status, ch, eol_cnt;
5685
5686 fp = generate_stream_from_string(s, &pid);
5687
5688 /* Now send results of command back into original context */
5689 setup_file_in_str(&pipe_str, fp);
5690 eol_cnt = 0;
5691 while ((ch = i_getch(&pipe_str)) != EOF) {
5692 if (ch == '\n') {
5693 eol_cnt++;
5694 continue;
5695 }
5696 while (eol_cnt) {
5697 o_addchr(dest, '\n');
5698 eol_cnt--;
5699 }
5700 o_addQchr(dest, ch);
5701 }
5702
5703 debug_printf("done reading from `cmd` pipe, closing it\n");
5704 fclose(fp);
5705 /* We need to extract exitcode. Test case
5706 * "true; echo `sleep 1; false` $?"
5707 * should print 1 */
5708 safe_waitpid(pid, &status, 0);
5709 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5710 return WEXITSTATUS(status);
5711}
5712#endif /* ENABLE_HUSH_TICK */
5713
5714
5715static void setup_heredoc(struct redir_struct *redir)
5716{
5717 struct fd_pair pair;
5718 pid_t pid;
5719 int len, written;
5720 /* the _body_ of heredoc (misleading field name) */
5721 const char *heredoc = redir->rd_filename;
5722 char *expanded;
5723#if !BB_MMU
5724 char **to_free;
5725#endif
5726
5727 expanded = NULL;
5728 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005729 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005730 if (expanded)
5731 heredoc = expanded;
5732 }
5733 len = strlen(heredoc);
5734
5735 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5736 xpiped_pair(pair);
5737 xmove_fd(pair.rd, redir->rd_fd);
5738
5739 /* Try writing without forking. Newer kernels have
5740 * dynamically growing pipes. Must use non-blocking write! */
5741 ndelay_on(pair.wr);
5742 while (1) {
5743 written = write(pair.wr, heredoc, len);
5744 if (written <= 0)
5745 break;
5746 len -= written;
5747 if (len == 0) {
5748 close(pair.wr);
5749 free(expanded);
5750 return;
5751 }
5752 heredoc += written;
5753 }
5754 ndelay_off(pair.wr);
5755
5756 /* Okay, pipe buffer was not big enough */
5757 /* Note: we must not create a stray child (bastard? :)
5758 * for the unsuspecting parent process. Child creates a grandchild
5759 * and exits before parent execs the process which consumes heredoc
5760 * (that exec happens after we return from this function) */
5761#if !BB_MMU
5762 to_free = NULL;
5763#endif
5764 pid = xvfork();
5765 if (pid == 0) {
5766 /* child */
5767 disable_restore_tty_pgrp_on_exit();
5768 pid = BB_MMU ? xfork() : xvfork();
5769 if (pid != 0)
5770 _exit(0);
5771 /* grandchild */
5772 close(redir->rd_fd); /* read side of the pipe */
5773#if BB_MMU
5774 full_write(pair.wr, heredoc, len); /* may loop or block */
5775 _exit(0);
5776#else
5777 /* Delegate blocking writes to another process */
5778 xmove_fd(pair.wr, STDOUT_FILENO);
5779 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5780#endif
5781 }
5782 /* parent */
5783#if ENABLE_HUSH_FAST
5784 G.count_SIGCHLD++;
5785//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5786#endif
5787 enable_restore_tty_pgrp_on_exit();
5788#if !BB_MMU
5789 free(to_free);
5790#endif
5791 close(pair.wr);
5792 free(expanded);
5793 wait(NULL); /* wait till child has died */
5794}
5795
5796/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5797 * and stderr if they are redirected. */
5798static int setup_redirects(struct command *prog, int squirrel[])
5799{
5800 int openfd, mode;
5801 struct redir_struct *redir;
5802
5803 for (redir = prog->redirects; redir; redir = redir->next) {
5804 if (redir->rd_type == REDIRECT_HEREDOC2) {
5805 /* rd_fd<<HERE case */
5806 if (squirrel && redir->rd_fd < 3
5807 && squirrel[redir->rd_fd] < 0
5808 ) {
5809 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5810 }
5811 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5812 * of the heredoc */
5813 debug_printf_parse("set heredoc '%s'\n",
5814 redir->rd_filename);
5815 setup_heredoc(redir);
5816 continue;
5817 }
5818
5819 if (redir->rd_dup == REDIRFD_TO_FILE) {
5820 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5821 char *p;
5822 if (redir->rd_filename == NULL) {
5823 /* Something went wrong in the parse.
5824 * Pretend it didn't happen */
5825 bb_error_msg("bug in redirect parse");
5826 continue;
5827 }
5828 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005829 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005830 openfd = open_or_warn(p, mode);
5831 free(p);
5832 if (openfd < 0) {
5833 /* this could get lost if stderr has been redirected, but
5834 * bash and ash both lose it as well (though zsh doesn't!) */
5835//what the above comment tries to say?
5836 return 1;
5837 }
5838 } else {
5839 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5840 openfd = redir->rd_dup;
5841 }
5842
5843 if (openfd != redir->rd_fd) {
5844 if (squirrel && redir->rd_fd < 3
5845 && squirrel[redir->rd_fd] < 0
5846 ) {
5847 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5848 }
5849 if (openfd == REDIRFD_CLOSE) {
5850 /* "n>-" means "close me" */
5851 close(redir->rd_fd);
5852 } else {
5853 xdup2(openfd, redir->rd_fd);
5854 if (redir->rd_dup == REDIRFD_TO_FILE)
5855 close(openfd);
5856 }
5857 }
5858 }
5859 return 0;
5860}
5861
5862static void restore_redirects(int squirrel[])
5863{
5864 int i, fd;
5865 for (i = 0; i < 3; i++) {
5866 fd = squirrel[i];
5867 if (fd != -1) {
5868 /* We simply die on error */
5869 xmove_fd(fd, i);
5870 }
5871 }
5872}
5873
5874static char *find_in_path(const char *arg)
5875{
5876 char *ret = NULL;
5877 const char *PATH = get_local_var_value("PATH");
5878
5879 if (!PATH)
5880 return NULL;
5881
5882 while (1) {
5883 const char *end = strchrnul(PATH, ':');
5884 int sz = end - PATH; /* must be int! */
5885
5886 free(ret);
5887 if (sz != 0) {
5888 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5889 } else {
5890 /* We have xxx::yyyy in $PATH,
5891 * it means "use current dir" */
5892 ret = xstrdup(arg);
5893 }
5894 if (access(ret, F_OK) == 0)
5895 break;
5896
5897 if (*end == '\0') {
5898 free(ret);
5899 return NULL;
5900 }
5901 PATH = end + 1;
5902 }
5903
5904 return ret;
5905}
5906
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005907static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005908 const struct built_in_command *x,
5909 const struct built_in_command *end)
5910{
5911 while (x != end) {
5912 if (strcmp(name, x->b_cmd) != 0) {
5913 x++;
5914 continue;
5915 }
5916 debug_printf_exec("found builtin '%s'\n", name);
5917 return x;
5918 }
5919 return NULL;
5920}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005921static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005922{
5923 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5924}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005925static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005926{
5927 const struct built_in_command *x = find_builtin1(name);
5928 if (x)
5929 return x;
5930 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5931}
5932
5933#if ENABLE_HUSH_FUNCTIONS
5934static struct function **find_function_slot(const char *name)
5935{
5936 struct function **funcpp = &G.top_func;
5937 while (*funcpp) {
5938 if (strcmp(name, (*funcpp)->name) == 0) {
5939 break;
5940 }
5941 funcpp = &(*funcpp)->next;
5942 }
5943 return funcpp;
5944}
5945
5946static const struct function *find_function(const char *name)
5947{
5948 const struct function *funcp = *find_function_slot(name);
5949 if (funcp)
5950 debug_printf_exec("found function '%s'\n", name);
5951 return funcp;
5952}
5953
5954/* Note: takes ownership on name ptr */
5955static struct function *new_function(char *name)
5956{
5957 struct function **funcpp = find_function_slot(name);
5958 struct function *funcp = *funcpp;
5959
5960 if (funcp != NULL) {
5961 struct command *cmd = funcp->parent_cmd;
5962 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5963 if (!cmd) {
5964 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5965 free(funcp->name);
5966 /* Note: if !funcp->body, do not free body_as_string!
5967 * This is a special case of "-F name body" function:
5968 * body_as_string was not malloced! */
5969 if (funcp->body) {
5970 free_pipe_list(funcp->body);
5971# if !BB_MMU
5972 free(funcp->body_as_string);
5973# endif
5974 }
5975 } else {
5976 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5977 cmd->argv[0] = funcp->name;
5978 cmd->group = funcp->body;
5979# if !BB_MMU
5980 cmd->group_as_string = funcp->body_as_string;
5981# endif
5982 }
5983 } else {
5984 debug_printf_exec("remembering new function '%s'\n", name);
5985 funcp = *funcpp = xzalloc(sizeof(*funcp));
5986 /*funcp->next = NULL;*/
5987 }
5988
5989 funcp->name = name;
5990 return funcp;
5991}
5992
5993static void unset_func(const char *name)
5994{
5995 struct function **funcpp = find_function_slot(name);
5996 struct function *funcp = *funcpp;
5997
5998 if (funcp != NULL) {
5999 debug_printf_exec("freeing function '%s'\n", funcp->name);
6000 *funcpp = funcp->next;
6001 /* funcp is unlinked now, deleting it.
6002 * Note: if !funcp->body, the function was created by
6003 * "-F name body", do not free ->body_as_string
6004 * and ->name as they were not malloced. */
6005 if (funcp->body) {
6006 free_pipe_list(funcp->body);
6007 free(funcp->name);
6008# if !BB_MMU
6009 free(funcp->body_as_string);
6010# endif
6011 }
6012 free(funcp);
6013 }
6014}
6015
6016# if BB_MMU
6017#define exec_function(to_free, funcp, argv) \
6018 exec_function(funcp, argv)
6019# endif
6020static void exec_function(char ***to_free,
6021 const struct function *funcp,
6022 char **argv) NORETURN;
6023static void exec_function(char ***to_free,
6024 const struct function *funcp,
6025 char **argv)
6026{
6027# if BB_MMU
6028 int n = 1;
6029
6030 argv[0] = G.global_argv[0];
6031 G.global_argv = argv;
6032 while (*++argv)
6033 n++;
6034 G.global_argc = n;
6035 /* On MMU, funcp->body is always non-NULL */
6036 n = run_list(funcp->body);
6037 fflush_all();
6038 _exit(n);
6039# else
6040 re_execute_shell(to_free,
6041 funcp->body_as_string,
6042 G.global_argv[0],
6043 argv + 1,
6044 NULL);
6045# endif
6046}
6047
6048static int run_function(const struct function *funcp, char **argv)
6049{
6050 int rc;
6051 save_arg_t sv;
6052 smallint sv_flg;
6053
6054 save_and_replace_G_args(&sv, argv);
6055
6056 /* "we are in function, ok to use return" */
6057 sv_flg = G.flag_return_in_progress;
6058 G.flag_return_in_progress = -1;
6059# if ENABLE_HUSH_LOCAL
6060 G.func_nest_level++;
6061# endif
6062
6063 /* On MMU, funcp->body is always non-NULL */
6064# if !BB_MMU
6065 if (!funcp->body) {
6066 /* Function defined by -F */
6067 parse_and_run_string(funcp->body_as_string);
6068 rc = G.last_exitcode;
6069 } else
6070# endif
6071 {
6072 rc = run_list(funcp->body);
6073 }
6074
6075# if ENABLE_HUSH_LOCAL
6076 {
6077 struct variable *var;
6078 struct variable **var_pp;
6079
6080 var_pp = &G.top_var;
6081 while ((var = *var_pp) != NULL) {
6082 if (var->func_nest_level < G.func_nest_level) {
6083 var_pp = &var->next;
6084 continue;
6085 }
6086 /* Unexport */
6087 if (var->flg_export)
6088 bb_unsetenv(var->varstr);
6089 /* Remove from global list */
6090 *var_pp = var->next;
6091 /* Free */
6092 if (!var->max_len)
6093 free(var->varstr);
6094 free(var);
6095 }
6096 G.func_nest_level--;
6097 }
6098# endif
6099 G.flag_return_in_progress = sv_flg;
6100
6101 restore_G_args(&sv, argv);
6102
6103 return rc;
6104}
6105#endif /* ENABLE_HUSH_FUNCTIONS */
6106
6107
6108#if BB_MMU
6109#define exec_builtin(to_free, x, argv) \
6110 exec_builtin(x, argv)
6111#else
6112#define exec_builtin(to_free, x, argv) \
6113 exec_builtin(to_free, argv)
6114#endif
6115static void exec_builtin(char ***to_free,
6116 const struct built_in_command *x,
6117 char **argv) NORETURN;
6118static void exec_builtin(char ***to_free,
6119 const struct built_in_command *x,
6120 char **argv)
6121{
6122#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006123 int rcode;
6124 fflush_all();
6125 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006126 fflush_all();
6127 _exit(rcode);
6128#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006129 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006130 /* On NOMMU, we must never block!
6131 * Example: { sleep 99 | read line; } & echo Ok
6132 */
6133 re_execute_shell(to_free,
6134 argv[0],
6135 G.global_argv[0],
6136 G.global_argv + 1,
6137 argv);
6138#endif
6139}
6140
6141
6142static void execvp_or_die(char **argv) NORETURN;
6143static void execvp_or_die(char **argv)
6144{
6145 debug_printf_exec("execing '%s'\n", argv[0]);
6146 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6147 execvp(argv[0], argv);
6148 bb_perror_msg("can't execute '%s'", argv[0]);
6149 _exit(127); /* bash compat */
6150}
6151
6152#if ENABLE_HUSH_MODE_X
6153static void dump_cmd_in_x_mode(char **argv)
6154{
6155 if (G_x_mode && argv) {
6156 /* We want to output the line in one write op */
6157 char *buf, *p;
6158 int len;
6159 int n;
6160
6161 len = 3;
6162 n = 0;
6163 while (argv[n])
6164 len += strlen(argv[n++]) + 1;
6165 buf = xmalloc(len);
6166 buf[0] = '+';
6167 p = buf + 1;
6168 n = 0;
6169 while (argv[n])
6170 p += sprintf(p, " %s", argv[n++]);
6171 *p++ = '\n';
6172 *p = '\0';
6173 fputs(buf, stderr);
6174 free(buf);
6175 }
6176}
6177#else
6178# define dump_cmd_in_x_mode(argv) ((void)0)
6179#endif
6180
6181#if BB_MMU
6182#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6183 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6184#define pseudo_exec(nommu_save, command, argv_expanded) \
6185 pseudo_exec(command, argv_expanded)
6186#endif
6187
6188/* Called after [v]fork() in run_pipe, or from builtin_exec.
6189 * Never returns.
6190 * Don't exit() here. If you don't exec, use _exit instead.
6191 * The at_exit handlers apparently confuse the calling process,
6192 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6193static void pseudo_exec_argv(nommu_save_t *nommu_save,
6194 char **argv, int assignment_cnt,
6195 char **argv_expanded) NORETURN;
6196static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6197 char **argv, int assignment_cnt,
6198 char **argv_expanded)
6199{
6200 char **new_env;
6201
6202 new_env = expand_assignments(argv, assignment_cnt);
6203 dump_cmd_in_x_mode(new_env);
6204
6205 if (!argv[assignment_cnt]) {
6206 /* Case when we are here: ... | var=val | ...
6207 * (note that we do not exit early, i.e., do not optimize out
6208 * expand_assignments(): think about ... | var=`sleep 1` | ...
6209 */
6210 free_strings(new_env);
6211 _exit(EXIT_SUCCESS);
6212 }
6213
6214#if BB_MMU
6215 set_vars_and_save_old(new_env);
6216 free(new_env); /* optional */
6217 /* we can also destroy set_vars_and_save_old's return value,
6218 * to save memory */
6219#else
6220 nommu_save->new_env = new_env;
6221 nommu_save->old_vars = set_vars_and_save_old(new_env);
6222#endif
6223
6224 if (argv_expanded) {
6225 argv = argv_expanded;
6226 } else {
6227 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6228#if !BB_MMU
6229 nommu_save->argv = argv;
6230#endif
6231 }
6232 dump_cmd_in_x_mode(argv);
6233
6234#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6235 if (strchr(argv[0], '/') != NULL)
6236 goto skip;
6237#endif
6238
6239 /* Check if the command matches any of the builtins.
6240 * Depending on context, this might be redundant. But it's
6241 * easier to waste a few CPU cycles than it is to figure out
6242 * if this is one of those cases.
6243 */
6244 {
6245 /* On NOMMU, it is more expensive to re-execute shell
6246 * just in order to run echo or test builtin.
6247 * It's better to skip it here and run corresponding
6248 * non-builtin later. */
6249 const struct built_in_command *x;
6250 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6251 if (x) {
6252 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6253 }
6254 }
6255#if ENABLE_HUSH_FUNCTIONS
6256 /* Check if the command matches any functions */
6257 {
6258 const struct function *funcp = find_function(argv[0]);
6259 if (funcp) {
6260 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6261 }
6262 }
6263#endif
6264
6265#if ENABLE_FEATURE_SH_STANDALONE
6266 /* Check if the command matches any busybox applets */
6267 {
6268 int a = find_applet_by_name(argv[0]);
6269 if (a >= 0) {
6270# if BB_MMU /* see above why on NOMMU it is not allowed */
6271 if (APPLET_IS_NOEXEC(a)) {
6272 debug_printf_exec("running applet '%s'\n", argv[0]);
6273 run_applet_no_and_exit(a, argv);
6274 }
6275# endif
6276 /* Re-exec ourselves */
6277 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6278 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6279 execv(bb_busybox_exec_path, argv);
6280 /* If they called chroot or otherwise made the binary no longer
6281 * executable, fall through */
6282 }
6283 }
6284#endif
6285
6286#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6287 skip:
6288#endif
6289 execvp_or_die(argv);
6290}
6291
6292/* Called after [v]fork() in run_pipe
6293 */
6294static void pseudo_exec(nommu_save_t *nommu_save,
6295 struct command *command,
6296 char **argv_expanded) NORETURN;
6297static void pseudo_exec(nommu_save_t *nommu_save,
6298 struct command *command,
6299 char **argv_expanded)
6300{
6301 if (command->argv) {
6302 pseudo_exec_argv(nommu_save, command->argv,
6303 command->assignment_cnt, argv_expanded);
6304 }
6305
6306 if (command->group) {
6307 /* Cases when we are here:
6308 * ( list )
6309 * { list } &
6310 * ... | ( list ) | ...
6311 * ... | { list } | ...
6312 */
6313#if BB_MMU
6314 int rcode;
6315 debug_printf_exec("pseudo_exec: run_list\n");
6316 reset_traps_to_defaults();
6317 rcode = run_list(command->group);
6318 /* OK to leak memory by not calling free_pipe_list,
6319 * since this process is about to exit */
6320 _exit(rcode);
6321#else
6322 re_execute_shell(&nommu_save->argv_from_re_execing,
6323 command->group_as_string,
6324 G.global_argv[0],
6325 G.global_argv + 1,
6326 NULL);
6327#endif
6328 }
6329
6330 /* Case when we are here: ... | >file */
6331 debug_printf_exec("pseudo_exec'ed null command\n");
6332 _exit(EXIT_SUCCESS);
6333}
6334
6335#if ENABLE_HUSH_JOB
6336static const char *get_cmdtext(struct pipe *pi)
6337{
6338 char **argv;
6339 char *p;
6340 int len;
6341
6342 /* This is subtle. ->cmdtext is created only on first backgrounding.
6343 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6344 * On subsequent bg argv is trashed, but we won't use it */
6345 if (pi->cmdtext)
6346 return pi->cmdtext;
6347 argv = pi->cmds[0].argv;
6348 if (!argv || !argv[0]) {
6349 pi->cmdtext = xzalloc(1);
6350 return pi->cmdtext;
6351 }
6352
6353 len = 0;
6354 do {
6355 len += strlen(*argv) + 1;
6356 } while (*++argv);
6357 p = xmalloc(len);
6358 pi->cmdtext = p;
6359 argv = pi->cmds[0].argv;
6360 do {
6361 len = strlen(*argv);
6362 memcpy(p, *argv, len);
6363 p += len;
6364 *p++ = ' ';
6365 } while (*++argv);
6366 p[-1] = '\0';
6367 return pi->cmdtext;
6368}
6369
6370static void insert_bg_job(struct pipe *pi)
6371{
6372 struct pipe *job, **jobp;
6373 int i;
6374
6375 /* Linear search for the ID of the job to use */
6376 pi->jobid = 1;
6377 for (job = G.job_list; job; job = job->next)
6378 if (job->jobid >= pi->jobid)
6379 pi->jobid = job->jobid + 1;
6380
6381 /* Add job to the list of running jobs */
6382 jobp = &G.job_list;
6383 while ((job = *jobp) != NULL)
6384 jobp = &job->next;
6385 job = *jobp = xmalloc(sizeof(*job));
6386
6387 *job = *pi; /* physical copy */
6388 job->next = NULL;
6389 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6390 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6391 for (i = 0; i < pi->num_cmds; i++) {
6392 job->cmds[i].pid = pi->cmds[i].pid;
6393 /* all other fields are not used and stay zero */
6394 }
6395 job->cmdtext = xstrdup(get_cmdtext(pi));
6396
6397 if (G_interactive_fd)
6398 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6399 G.last_jobid = job->jobid;
6400}
6401
6402static void remove_bg_job(struct pipe *pi)
6403{
6404 struct pipe *prev_pipe;
6405
6406 if (pi == G.job_list) {
6407 G.job_list = pi->next;
6408 } else {
6409 prev_pipe = G.job_list;
6410 while (prev_pipe->next != pi)
6411 prev_pipe = prev_pipe->next;
6412 prev_pipe->next = pi->next;
6413 }
6414 if (G.job_list)
6415 G.last_jobid = G.job_list->jobid;
6416 else
6417 G.last_jobid = 0;
6418}
6419
6420/* Remove a backgrounded job */
6421static void delete_finished_bg_job(struct pipe *pi)
6422{
6423 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006424 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006425}
6426#endif /* JOB */
6427
6428/* Check to see if any processes have exited -- if they
6429 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006430static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006431{
6432 int attributes;
6433 int status;
6434#if ENABLE_HUSH_JOB
6435 struct pipe *pi;
6436#endif
6437 pid_t childpid;
6438 int rcode = 0;
6439
6440 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6441
6442 attributes = WUNTRACED;
6443 if (fg_pipe == NULL)
6444 attributes |= WNOHANG;
6445
6446 errno = 0;
6447#if ENABLE_HUSH_FAST
6448 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6449//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6450//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6451 /* There was neither fork nor SIGCHLD since last waitpid */
6452 /* Avoid doing waitpid syscall if possible */
6453 if (!G.we_have_children) {
6454 errno = ECHILD;
6455 return -1;
6456 }
6457 if (fg_pipe == NULL) { /* is WNOHANG set? */
6458 /* We have children, but they did not exit
6459 * or stop yet (we saw no SIGCHLD) */
6460 return 0;
6461 }
6462 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6463 }
6464#endif
6465
6466/* Do we do this right?
6467 * bash-3.00# sleep 20 | false
6468 * <ctrl-Z pressed>
6469 * [3]+ Stopped sleep 20 | false
6470 * bash-3.00# echo $?
6471 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6472 * [hush 1.14.0: yes we do it right]
6473 */
6474 wait_more:
6475 while (1) {
6476 int i;
6477 int dead;
6478
6479#if ENABLE_HUSH_FAST
6480 i = G.count_SIGCHLD;
6481#endif
6482 childpid = waitpid(-1, &status, attributes);
6483 if (childpid <= 0) {
6484 if (childpid && errno != ECHILD)
6485 bb_perror_msg("waitpid");
6486#if ENABLE_HUSH_FAST
6487 else { /* Until next SIGCHLD, waitpid's are useless */
6488 G.we_have_children = (childpid == 0);
6489 G.handled_SIGCHLD = i;
6490//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6491 }
6492#endif
6493 break;
6494 }
6495 dead = WIFEXITED(status) || WIFSIGNALED(status);
6496
6497#if DEBUG_JOBS
6498 if (WIFSTOPPED(status))
6499 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6500 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6501 if (WIFSIGNALED(status))
6502 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6503 childpid, WTERMSIG(status), WEXITSTATUS(status));
6504 if (WIFEXITED(status))
6505 debug_printf_jobs("pid %d exited, exitcode %d\n",
6506 childpid, WEXITSTATUS(status));
6507#endif
6508 /* Were we asked to wait for fg pipe? */
6509 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006510 i = fg_pipe->num_cmds;
6511 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006512 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6513 if (fg_pipe->cmds[i].pid != childpid)
6514 continue;
6515 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006516 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006517 fg_pipe->cmds[i].pid = 0;
6518 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006519 ex = WEXITSTATUS(status);
6520 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006521 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006522 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6523 */
6524 if (WIFSIGNALED(status)) {
6525 int sig = WTERMSIG(status);
6526 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006527 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6528 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6529 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006530 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6531 * Maybe we need to use sig | 128? */
6532 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006533 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006534 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006535 } else {
6536 fg_pipe->cmds[i].is_stopped = 1;
6537 fg_pipe->stopped_cmds++;
6538 }
6539 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6540 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006541 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006542 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006543 i = fg_pipe->num_cmds;
6544 while (--i >= 0) {
6545 rcode = fg_pipe->cmds[i].cmd_exitcode;
6546 /* usually last process gives overall exitstatus,
6547 * but with "set -o pipefail", last *failed* process does */
6548 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6549 break;
6550 }
6551 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006552/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6553 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6554 * and "killall -STOP cat" */
6555 if (G_interactive_fd) {
6556#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006557 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006558 insert_bg_job(fg_pipe);
6559#endif
6560 return rcode;
6561 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006562 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006563 return rcode;
6564 }
6565 /* There are still running processes in the fg pipe */
6566 goto wait_more; /* do waitpid again */
6567 }
6568 /* it wasnt fg_pipe, look for process in bg pipes */
6569 }
6570
6571#if ENABLE_HUSH_JOB
6572 /* We asked to wait for bg or orphaned children */
6573 /* No need to remember exitcode in this case */
6574 for (pi = G.job_list; pi; pi = pi->next) {
6575 for (i = 0; i < pi->num_cmds; i++) {
6576 if (pi->cmds[i].pid == childpid)
6577 goto found_pi_and_prognum;
6578 }
6579 }
6580 /* Happens when shell is used as init process (init=/bin/sh) */
6581 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6582 continue; /* do waitpid again */
6583
6584 found_pi_and_prognum:
6585 if (dead) {
6586 /* child exited */
6587 pi->cmds[i].pid = 0;
6588 pi->alive_cmds--;
6589 if (!pi->alive_cmds) {
6590 if (G_interactive_fd)
6591 printf(JOB_STATUS_FORMAT, pi->jobid,
6592 "Done", pi->cmdtext);
6593 delete_finished_bg_job(pi);
6594 }
6595 } else {
6596 /* child stopped */
6597 pi->cmds[i].is_stopped = 1;
6598 pi->stopped_cmds++;
6599 }
6600#endif
6601 } /* while (waitpid succeeds)... */
6602
6603 return rcode;
6604}
6605
6606#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006607static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006608{
6609 pid_t p;
6610 int rcode = checkjobs(fg_pipe);
6611 if (G_saved_tty_pgrp) {
6612 /* Job finished, move the shell to the foreground */
6613 p = getpgrp(); /* our process group id */
6614 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6615 tcsetpgrp(G_interactive_fd, p);
6616 }
6617 return rcode;
6618}
6619#endif
6620
6621/* Start all the jobs, but don't wait for anything to finish.
6622 * See checkjobs().
6623 *
6624 * Return code is normally -1, when the caller has to wait for children
6625 * to finish to determine the exit status of the pipe. If the pipe
6626 * is a simple builtin command, however, the action is done by the
6627 * time run_pipe returns, and the exit code is provided as the
6628 * return value.
6629 *
6630 * Returns -1 only if started some children. IOW: we have to
6631 * mask out retvals of builtins etc with 0xff!
6632 *
6633 * The only case when we do not need to [v]fork is when the pipe
6634 * is single, non-backgrounded, non-subshell command. Examples:
6635 * cmd ; ... { list } ; ...
6636 * cmd && ... { list } && ...
6637 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006638 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006639 * or (if SH_STANDALONE) an applet, and we can run the { list }
6640 * with run_list. If it isn't one of these, we fork and exec cmd.
6641 *
6642 * Cases when we must fork:
6643 * non-single: cmd | cmd
6644 * backgrounded: cmd & { list } &
6645 * subshell: ( list ) [&]
6646 */
6647#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006648#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006649 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6650#endif
6651static int redirect_and_varexp_helper(char ***new_env_p,
6652 struct variable **old_vars_p,
6653 struct command *command,
6654 int squirrel[3],
6655 char **argv_expanded)
6656{
6657 /* setup_redirects acts on file descriptors, not FILEs.
6658 * This is perfect for work that comes after exec().
6659 * Is it really safe for inline use? Experimentally,
6660 * things seem to work. */
6661 int rcode = setup_redirects(command, squirrel);
6662 if (rcode == 0) {
6663 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6664 *new_env_p = new_env;
6665 dump_cmd_in_x_mode(new_env);
6666 dump_cmd_in_x_mode(argv_expanded);
6667 if (old_vars_p)
6668 *old_vars_p = set_vars_and_save_old(new_env);
6669 }
6670 return rcode;
6671}
6672static NOINLINE int run_pipe(struct pipe *pi)
6673{
6674 static const char *const null_ptr = NULL;
6675
6676 int cmd_no;
6677 int next_infd;
6678 struct command *command;
6679 char **argv_expanded;
6680 char **argv;
6681 /* it is not always needed, but we aim to smaller code */
6682 int squirrel[] = { -1, -1, -1 };
6683 int rcode;
6684
6685 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6686 debug_enter();
6687
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006688 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6689 * Result should be 3 lines: q w e, qwe, q w e
6690 */
6691 G.ifs = get_local_var_value("IFS");
6692 if (!G.ifs)
6693 G.ifs = defifs;
6694
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006695 IF_HUSH_JOB(pi->pgrp = -1;)
6696 pi->stopped_cmds = 0;
6697 command = &pi->cmds[0];
6698 argv_expanded = NULL;
6699
6700 if (pi->num_cmds != 1
6701 || pi->followup == PIPE_BG
6702 || command->cmd_type == CMD_SUBSHELL
6703 ) {
6704 goto must_fork;
6705 }
6706
6707 pi->alive_cmds = 1;
6708
6709 debug_printf_exec(": group:%p argv:'%s'\n",
6710 command->group, command->argv ? command->argv[0] : "NONE");
6711
6712 if (command->group) {
6713#if ENABLE_HUSH_FUNCTIONS
6714 if (command->cmd_type == CMD_FUNCDEF) {
6715 /* "executing" func () { list } */
6716 struct function *funcp;
6717
6718 funcp = new_function(command->argv[0]);
6719 /* funcp->name is already set to argv[0] */
6720 funcp->body = command->group;
6721# if !BB_MMU
6722 funcp->body_as_string = command->group_as_string;
6723 command->group_as_string = NULL;
6724# endif
6725 command->group = NULL;
6726 command->argv[0] = NULL;
6727 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6728 funcp->parent_cmd = command;
6729 command->child_func = funcp;
6730
6731 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6732 debug_leave();
6733 return EXIT_SUCCESS;
6734 }
6735#endif
6736 /* { list } */
6737 debug_printf("non-subshell group\n");
6738 rcode = 1; /* exitcode if redir failed */
6739 if (setup_redirects(command, squirrel) == 0) {
6740 debug_printf_exec(": run_list\n");
6741 rcode = run_list(command->group) & 0xff;
6742 }
6743 restore_redirects(squirrel);
6744 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6745 debug_leave();
6746 debug_printf_exec("run_pipe: return %d\n", rcode);
6747 return rcode;
6748 }
6749
6750 argv = command->argv ? command->argv : (char **) &null_ptr;
6751 {
6752 const struct built_in_command *x;
6753#if ENABLE_HUSH_FUNCTIONS
6754 const struct function *funcp;
6755#else
6756 enum { funcp = 0 };
6757#endif
6758 char **new_env = NULL;
6759 struct variable *old_vars = NULL;
6760
6761 if (argv[command->assignment_cnt] == NULL) {
6762 /* Assignments, but no command */
6763 /* Ensure redirects take effect (that is, create files).
6764 * Try "a=t >file" */
6765#if 0 /* A few cases in testsuite fail with this code. FIXME */
6766 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6767 /* Set shell variables */
6768 if (new_env) {
6769 argv = new_env;
6770 while (*argv) {
6771 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6772 /* Do we need to flag set_local_var() errors?
6773 * "assignment to readonly var" and "putenv error"
6774 */
6775 argv++;
6776 }
6777 }
6778 /* Redirect error sets $? to 1. Otherwise,
6779 * if evaluating assignment value set $?, retain it.
6780 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6781 if (rcode == 0)
6782 rcode = G.last_exitcode;
6783 /* Exit, _skipping_ variable restoring code: */
6784 goto clean_up_and_ret0;
6785
6786#else /* Older, bigger, but more correct code */
6787
6788 rcode = setup_redirects(command, squirrel);
6789 restore_redirects(squirrel);
6790 /* Set shell variables */
6791 if (G_x_mode)
6792 bb_putchar_stderr('+');
6793 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006794 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006795 if (G_x_mode)
6796 fprintf(stderr, " %s", p);
6797 debug_printf_exec("set shell var:'%s'->'%s'\n",
6798 *argv, p);
6799 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6800 /* Do we need to flag set_local_var() errors?
6801 * "assignment to readonly var" and "putenv error"
6802 */
6803 argv++;
6804 }
6805 if (G_x_mode)
6806 bb_putchar_stderr('\n');
6807 /* Redirect error sets $? to 1. Otherwise,
6808 * if evaluating assignment value set $?, retain it.
6809 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6810 if (rcode == 0)
6811 rcode = G.last_exitcode;
6812 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6813 debug_leave();
6814 debug_printf_exec("run_pipe: return %d\n", rcode);
6815 return rcode;
6816#endif
6817 }
6818
6819 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006820#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006821 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006822 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006823 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006824#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006825 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006826 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6827 }
6828
6829 /* if someone gives us an empty string: `cmd with empty output` */
6830 if (!argv_expanded[0]) {
6831 free(argv_expanded);
6832 debug_leave();
6833 return G.last_exitcode;
6834 }
6835
6836 x = find_builtin(argv_expanded[0]);
6837#if ENABLE_HUSH_FUNCTIONS
6838 funcp = NULL;
6839 if (!x)
6840 funcp = find_function(argv_expanded[0]);
6841#endif
6842 if (x || funcp) {
6843 if (!funcp) {
6844 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6845 debug_printf("exec with redirects only\n");
6846 rcode = setup_redirects(command, NULL);
6847 goto clean_up_and_ret1;
6848 }
6849 }
6850 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6851 if (rcode == 0) {
6852 if (!funcp) {
6853 debug_printf_exec(": builtin '%s' '%s'...\n",
6854 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006855 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006856 rcode = x->b_function(argv_expanded) & 0xff;
6857 fflush_all();
6858 }
6859#if ENABLE_HUSH_FUNCTIONS
6860 else {
6861# if ENABLE_HUSH_LOCAL
6862 struct variable **sv;
6863 sv = G.shadowed_vars_pp;
6864 G.shadowed_vars_pp = &old_vars;
6865# endif
6866 debug_printf_exec(": function '%s' '%s'...\n",
6867 funcp->name, argv_expanded[1]);
6868 rcode = run_function(funcp, argv_expanded) & 0xff;
6869# if ENABLE_HUSH_LOCAL
6870 G.shadowed_vars_pp = sv;
6871# endif
6872 }
6873#endif
6874 }
6875 clean_up_and_ret:
6876 unset_vars(new_env);
6877 add_vars(old_vars);
6878/* clean_up_and_ret0: */
6879 restore_redirects(squirrel);
6880 clean_up_and_ret1:
6881 free(argv_expanded);
6882 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6883 debug_leave();
6884 debug_printf_exec("run_pipe return %d\n", rcode);
6885 return rcode;
6886 }
6887
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006888 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006889 int n = find_applet_by_name(argv_expanded[0]);
6890 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6891 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6892 if (rcode == 0) {
6893 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6894 argv_expanded[0], argv_expanded[1]);
6895 rcode = run_nofork_applet(n, argv_expanded);
6896 }
6897 goto clean_up_and_ret;
6898 }
6899 }
6900 /* It is neither builtin nor applet. We must fork. */
6901 }
6902
6903 must_fork:
6904 /* NB: argv_expanded may already be created, and that
6905 * might include `cmd` runs! Do not rerun it! We *must*
6906 * use argv_expanded if it's non-NULL */
6907
6908 /* Going to fork a child per each pipe member */
6909 pi->alive_cmds = 0;
6910 next_infd = 0;
6911
6912 cmd_no = 0;
6913 while (cmd_no < pi->num_cmds) {
6914 struct fd_pair pipefds;
6915#if !BB_MMU
6916 volatile nommu_save_t nommu_save;
6917 nommu_save.new_env = NULL;
6918 nommu_save.old_vars = NULL;
6919 nommu_save.argv = NULL;
6920 nommu_save.argv_from_re_execing = NULL;
6921#endif
6922 command = &pi->cmds[cmd_no];
6923 cmd_no++;
6924 if (command->argv) {
6925 debug_printf_exec(": pipe member '%s' '%s'...\n",
6926 command->argv[0], command->argv[1]);
6927 } else {
6928 debug_printf_exec(": pipe member with no argv\n");
6929 }
6930
6931 /* pipes are inserted between pairs of commands */
6932 pipefds.rd = 0;
6933 pipefds.wr = 1;
6934 if (cmd_no < pi->num_cmds)
6935 xpiped_pair(pipefds);
6936
6937 command->pid = BB_MMU ? fork() : vfork();
6938 if (!command->pid) { /* child */
6939#if ENABLE_HUSH_JOB
6940 disable_restore_tty_pgrp_on_exit();
6941 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6942
6943 /* Every child adds itself to new process group
6944 * with pgid == pid_of_first_child_in_pipe */
6945 if (G.run_list_level == 1 && G_interactive_fd) {
6946 pid_t pgrp;
6947 pgrp = pi->pgrp;
6948 if (pgrp < 0) /* true for 1st process only */
6949 pgrp = getpid();
6950 if (setpgid(0, pgrp) == 0
6951 && pi->followup != PIPE_BG
6952 && G_saved_tty_pgrp /* we have ctty */
6953 ) {
6954 /* We do it in *every* child, not just first,
6955 * to avoid races */
6956 tcsetpgrp(G_interactive_fd, pgrp);
6957 }
6958 }
6959#endif
6960 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6961 /* 1st cmd in backgrounded pipe
6962 * should have its stdin /dev/null'ed */
6963 close(0);
6964 if (open(bb_dev_null, O_RDONLY))
6965 xopen("/", O_RDONLY);
6966 } else {
6967 xmove_fd(next_infd, 0);
6968 }
6969 xmove_fd(pipefds.wr, 1);
6970 if (pipefds.rd > 1)
6971 close(pipefds.rd);
6972 /* Like bash, explicit redirects override pipes,
6973 * and the pipe fd is available for dup'ing. */
6974 if (setup_redirects(command, NULL))
6975 _exit(1);
6976
6977 /* Restore default handlers just prior to exec */
6978 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6979
6980 /* Stores to nommu_save list of env vars putenv'ed
6981 * (NOMMU, on MMU we don't need that) */
6982 /* cast away volatility... */
6983 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6984 /* pseudo_exec() does not return */
6985 }
6986
6987 /* parent or error */
6988#if ENABLE_HUSH_FAST
6989 G.count_SIGCHLD++;
6990//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6991#endif
6992 enable_restore_tty_pgrp_on_exit();
6993#if !BB_MMU
6994 /* Clean up after vforked child */
6995 free(nommu_save.argv);
6996 free(nommu_save.argv_from_re_execing);
6997 unset_vars(nommu_save.new_env);
6998 add_vars(nommu_save.old_vars);
6999#endif
7000 free(argv_expanded);
7001 argv_expanded = NULL;
7002 if (command->pid < 0) { /* [v]fork failed */
7003 /* Clearly indicate, was it fork or vfork */
7004 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7005 } else {
7006 pi->alive_cmds++;
7007#if ENABLE_HUSH_JOB
7008 /* Second and next children need to know pid of first one */
7009 if (pi->pgrp < 0)
7010 pi->pgrp = command->pid;
7011#endif
7012 }
7013
7014 if (cmd_no > 1)
7015 close(next_infd);
7016 if (cmd_no < pi->num_cmds)
7017 close(pipefds.wr);
7018 /* Pass read (output) pipe end to next iteration */
7019 next_infd = pipefds.rd;
7020 }
7021
7022 if (!pi->alive_cmds) {
7023 debug_leave();
7024 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7025 return 1;
7026 }
7027
7028 debug_leave();
7029 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7030 return -1;
7031}
7032
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007033/* NB: called by pseudo_exec, and therefore must not modify any
7034 * global data until exec/_exit (we can be a child after vfork!) */
7035static int run_list(struct pipe *pi)
7036{
7037#if ENABLE_HUSH_CASE
7038 char *case_word = NULL;
7039#endif
7040#if ENABLE_HUSH_LOOPS
7041 struct pipe *loop_top = NULL;
7042 char **for_lcur = NULL;
7043 char **for_list = NULL;
7044#endif
7045 smallint last_followup;
7046 smalluint rcode;
7047#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7048 smalluint cond_code = 0;
7049#else
7050 enum { cond_code = 0 };
7051#endif
7052#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007053 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007054 smallint last_rword; /* ditto */
7055#endif
7056
7057 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7058 debug_enter();
7059
7060#if ENABLE_HUSH_LOOPS
7061 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007062 {
7063 struct pipe *cpipe;
7064 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7065 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7066 continue;
7067 /* current word is FOR or IN (BOLD in comments below) */
7068 if (cpipe->next == NULL) {
7069 syntax_error("malformed for");
7070 debug_leave();
7071 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7072 return 1;
7073 }
7074 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7075 if (cpipe->next->res_word == RES_DO)
7076 continue;
7077 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7078 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7079 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7080 ) {
7081 syntax_error("malformed for");
7082 debug_leave();
7083 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7084 return 1;
7085 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007086 }
7087 }
7088#endif
7089
7090 /* Past this point, all code paths should jump to ret: label
7091 * in order to return, no direct "return" statements please.
7092 * This helps to ensure that no memory is leaked. */
7093
7094#if ENABLE_HUSH_JOB
7095 G.run_list_level++;
7096#endif
7097
7098#if HAS_KEYWORDS
7099 rword = RES_NONE;
7100 last_rword = RES_XXXX;
7101#endif
7102 last_followup = PIPE_SEQ;
7103 rcode = G.last_exitcode;
7104
7105 /* Go through list of pipes, (maybe) executing them. */
7106 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7107 if (G.flag_SIGINT)
7108 break;
7109
7110 IF_HAS_KEYWORDS(rword = pi->res_word;)
7111 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7112 rword, cond_code, last_rword);
7113#if ENABLE_HUSH_LOOPS
7114 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7115 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7116 ) {
7117 /* start of a loop: remember where loop starts */
7118 loop_top = pi;
7119 G.depth_of_loop++;
7120 }
7121#endif
7122 /* Still in the same "if...", "then..." or "do..." branch? */
7123 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7124 if ((rcode == 0 && last_followup == PIPE_OR)
7125 || (rcode != 0 && last_followup == PIPE_AND)
7126 ) {
7127 /* It is "<true> || CMD" or "<false> && CMD"
7128 * and we should not execute CMD */
7129 debug_printf_exec("skipped cmd because of || or &&\n");
7130 last_followup = pi->followup;
7131 continue;
7132 }
7133 }
7134 last_followup = pi->followup;
7135 IF_HAS_KEYWORDS(last_rword = rword;)
7136#if ENABLE_HUSH_IF
7137 if (cond_code) {
7138 if (rword == RES_THEN) {
7139 /* if false; then ... fi has exitcode 0! */
7140 G.last_exitcode = rcode = EXIT_SUCCESS;
7141 /* "if <false> THEN cmd": skip cmd */
7142 continue;
7143 }
7144 } else {
7145 if (rword == RES_ELSE || rword == RES_ELIF) {
7146 /* "if <true> then ... ELSE/ELIF cmd":
7147 * skip cmd and all following ones */
7148 break;
7149 }
7150 }
7151#endif
7152#if ENABLE_HUSH_LOOPS
7153 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7154 if (!for_lcur) {
7155 /* first loop through for */
7156
7157 static const char encoded_dollar_at[] ALIGN1 = {
7158 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7159 }; /* encoded representation of "$@" */
7160 static const char *const encoded_dollar_at_argv[] = {
7161 encoded_dollar_at, NULL
7162 }; /* argv list with one element: "$@" */
7163 char **vals;
7164
7165 vals = (char**)encoded_dollar_at_argv;
7166 if (pi->next->res_word == RES_IN) {
7167 /* if no variable values after "in" we skip "for" */
7168 if (!pi->next->cmds[0].argv) {
7169 G.last_exitcode = rcode = EXIT_SUCCESS;
7170 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7171 break;
7172 }
7173 vals = pi->next->cmds[0].argv;
7174 } /* else: "for var; do..." -> assume "$@" list */
7175 /* create list of variable values */
7176 debug_print_strings("for_list made from", vals);
7177 for_list = expand_strvec_to_strvec(vals);
7178 for_lcur = for_list;
7179 debug_print_strings("for_list", for_list);
7180 }
7181 if (!*for_lcur) {
7182 /* "for" loop is over, clean up */
7183 free(for_list);
7184 for_list = NULL;
7185 for_lcur = NULL;
7186 break;
7187 }
7188 /* Insert next value from for_lcur */
7189 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7190 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7191 continue;
7192 }
7193 if (rword == RES_IN) {
7194 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7195 }
7196 if (rword == RES_DONE) {
7197 continue; /* "done" has no cmds too */
7198 }
7199#endif
7200#if ENABLE_HUSH_CASE
7201 if (rword == RES_CASE) {
7202 case_word = expand_strvec_to_string(pi->cmds->argv);
7203 continue;
7204 }
7205 if (rword == RES_MATCH) {
7206 char **argv;
7207
7208 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7209 break;
7210 /* all prev words didn't match, does this one match? */
7211 argv = pi->cmds->argv;
7212 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007213 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007214 /* TODO: which FNM_xxx flags to use? */
7215 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7216 free(pattern);
7217 if (cond_code == 0) { /* match! we will execute this branch */
7218 free(case_word); /* make future "word)" stop */
7219 case_word = NULL;
7220 break;
7221 }
7222 argv++;
7223 }
7224 continue;
7225 }
7226 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7227 if (cond_code != 0)
7228 continue; /* not matched yet, skip this pipe */
7229 }
7230#endif
7231 /* Just pressing <enter> in shell should check for jobs.
7232 * OTOH, in non-interactive shell this is useless
7233 * and only leads to extra job checks */
7234 if (pi->num_cmds == 0) {
7235 if (G_interactive_fd)
7236 goto check_jobs_and_continue;
7237 continue;
7238 }
7239
7240 /* After analyzing all keywords and conditions, we decided
7241 * to execute this pipe. NB: have to do checkjobs(NULL)
7242 * after run_pipe to collect any background children,
7243 * even if list execution is to be stopped. */
7244 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7245 {
7246 int r;
7247#if ENABLE_HUSH_LOOPS
7248 G.flag_break_continue = 0;
7249#endif
7250 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7251 if (r != -1) {
7252 /* We ran a builtin, function, or group.
7253 * rcode is already known
7254 * and we don't need to wait for anything. */
7255 G.last_exitcode = rcode;
7256 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7257 check_and_run_traps(0);
7258#if ENABLE_HUSH_LOOPS
7259 /* Was it "break" or "continue"? */
7260 if (G.flag_break_continue) {
7261 smallint fbc = G.flag_break_continue;
7262 /* We might fall into outer *loop*,
7263 * don't want to break it too */
7264 if (loop_top) {
7265 G.depth_break_continue--;
7266 if (G.depth_break_continue == 0)
7267 G.flag_break_continue = 0;
7268 /* else: e.g. "continue 2" should *break* once, *then* continue */
7269 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7270 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7271 goto check_jobs_and_break;
7272 /* "continue": simulate end of loop */
7273 rword = RES_DONE;
7274 continue;
7275 }
7276#endif
7277#if ENABLE_HUSH_FUNCTIONS
7278 if (G.flag_return_in_progress == 1) {
7279 /* same as "goto check_jobs_and_break" */
7280 checkjobs(NULL);
7281 break;
7282 }
7283#endif
7284 } else if (pi->followup == PIPE_BG) {
7285 /* What does bash do with attempts to background builtins? */
7286 /* even bash 3.2 doesn't do that well with nested bg:
7287 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7288 * I'm NOT treating inner &'s as jobs */
7289 check_and_run_traps(0);
7290#if ENABLE_HUSH_JOB
7291 if (G.run_list_level == 1)
7292 insert_bg_job(pi);
7293#endif
7294 /* Last command's pid goes to $! */
7295 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7296 G.last_exitcode = rcode = EXIT_SUCCESS;
7297 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7298 } else {
7299#if ENABLE_HUSH_JOB
7300 if (G.run_list_level == 1 && G_interactive_fd) {
7301 /* Waits for completion, then fg's main shell */
7302 rcode = checkjobs_and_fg_shell(pi);
7303 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7304 check_and_run_traps(0);
7305 } else
7306#endif
7307 { /* This one just waits for completion */
7308 rcode = checkjobs(pi);
7309 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7310 check_and_run_traps(0);
7311 }
7312 G.last_exitcode = rcode;
7313 }
7314 }
7315
7316 /* Analyze how result affects subsequent commands */
7317#if ENABLE_HUSH_IF
7318 if (rword == RES_IF || rword == RES_ELIF)
7319 cond_code = rcode;
7320#endif
7321#if ENABLE_HUSH_LOOPS
7322 /* Beware of "while false; true; do ..."! */
7323 if (pi->next && pi->next->res_word == RES_DO) {
7324 if (rword == RES_WHILE) {
7325 if (rcode) {
7326 /* "while false; do...done" - exitcode 0 */
7327 G.last_exitcode = rcode = EXIT_SUCCESS;
7328 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7329 goto check_jobs_and_break;
7330 }
7331 }
7332 if (rword == RES_UNTIL) {
7333 if (!rcode) {
7334 debug_printf_exec(": until expr is true: breaking\n");
7335 check_jobs_and_break:
7336 checkjobs(NULL);
7337 break;
7338 }
7339 }
7340 }
7341#endif
7342
7343 check_jobs_and_continue:
7344 checkjobs(NULL);
7345 } /* for (pi) */
7346
7347#if ENABLE_HUSH_JOB
7348 G.run_list_level--;
7349#endif
7350#if ENABLE_HUSH_LOOPS
7351 if (loop_top)
7352 G.depth_of_loop--;
7353 free(for_list);
7354#endif
7355#if ENABLE_HUSH_CASE
7356 free(case_word);
7357#endif
7358 debug_leave();
7359 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7360 return rcode;
7361}
7362
7363/* Select which version we will use */
7364static int run_and_free_list(struct pipe *pi)
7365{
7366 int rcode = 0;
7367 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007368 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007369 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7370 rcode = run_list(pi);
7371 }
7372 /* free_pipe_list has the side effect of clearing memory.
7373 * In the long run that function can be merged with run_list,
7374 * but doing that now would hobble the debugging effort. */
7375 free_pipe_list(pi);
7376 debug_printf_exec("run_and_free_list return %d\n", rcode);
7377 return rcode;
7378}
7379
7380
Denis Vlasenkof9375282009-04-05 19:13:39 +00007381/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007382static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007383{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007384 unsigned sig;
7385 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007386 sigset_t old_blocked_set;
7387
7388 if (!G.inherited_set_is_saved) {
7389 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7390 G.inherited_set = G.blocked_set;
7391 }
7392 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007393
Denis Vlasenkof9375282009-04-05 19:13:39 +00007394 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007395 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007396 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007397 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007398 mask |= SPECIAL_JOB_SIGS;
7399 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007400 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007401
Denis Vlasenkof9375282009-04-05 19:13:39 +00007402 sig = 0;
7403 while (mask) {
7404 if (mask & 1)
7405 sigaddset(&G.blocked_set, sig);
7406 mask >>= 1;
7407 sig++;
7408 }
7409 sigdelset(&G.blocked_set, SIGCHLD);
7410
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007411 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7412 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7413
Denis Vlasenkof9375282009-04-05 19:13:39 +00007414 /* POSIX allows shell to re-enable SIGCHLD
7415 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007416#if ENABLE_HUSH_FAST
7417 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007418 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007419 signal(SIGCHLD, SIGCHLD_handler);
7420#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007421 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007422 signal(SIGCHLD, SIG_DFL);
7423#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007424
7425 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007426}
7427
7428#if ENABLE_HUSH_JOB
7429/* helper */
7430static void maybe_set_to_sigexit(int sig)
7431{
7432 void (*handler)(int);
7433 /* non_DFL_mask'ed signals are, well, masked,
7434 * no need to set handler for them.
7435 */
7436 if (!((G.non_DFL_mask >> sig) & 1)) {
7437 handler = signal(sig, sigexit);
7438 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7439 signal(sig, handler);
7440 }
7441}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007442/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007443static void set_fatal_handlers(void)
7444{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007445 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007446 if (HUSH_DEBUG) {
7447 maybe_set_to_sigexit(SIGILL );
7448 maybe_set_to_sigexit(SIGFPE );
7449 maybe_set_to_sigexit(SIGBUS );
7450 maybe_set_to_sigexit(SIGSEGV);
7451 maybe_set_to_sigexit(SIGTRAP);
7452 } /* else: hush is perfect. what SEGV? */
7453 maybe_set_to_sigexit(SIGABRT);
7454 /* bash 3.2 seems to handle these just like 'fatal' ones */
7455 maybe_set_to_sigexit(SIGPIPE);
7456 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007457 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007458 * if we aren't interactive... but in this case
7459 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007460 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007461 /*maybe_set_to_sigexit(SIGTERM);*/
7462 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007463}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007464#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007465
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007466static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007467{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007468 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007469 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007470 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007471 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007472 break;
7473 case 'x':
7474 IF_HUSH_MODE_X(G_x_mode = state;)
7475 break;
7476 case 'o':
7477 if (!o_opt) {
7478 /* "set -+o" without parameter.
7479 * in bash, set -o produces this output:
7480 * pipefail off
7481 * and set +o:
7482 * set +o pipefail
7483 * We always use the second form.
7484 */
7485 const char *p = o_opt_strings;
7486 idx = 0;
7487 while (*p) {
7488 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7489 idx++;
7490 p += strlen(p) + 1;
7491 }
7492 break;
7493 }
7494 idx = index_in_strings(o_opt_strings, o_opt);
7495 if (idx >= 0) {
7496 G.o_opt[idx] = state;
7497 break;
7498 }
7499 default:
7500 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007501 }
7502 return EXIT_SUCCESS;
7503}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007504
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007505int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007506int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007507{
7508 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007509 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007510 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007511 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007512 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007513
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007514 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007515 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007516 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007517#if !BB_MMU
7518 G.argv0_for_re_execing = argv[0];
7519#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007520 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007521 shell_ver = xzalloc(sizeof(*shell_ver));
7522 shell_ver->flg_export = 1;
7523 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007524 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007525 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007526 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007527 /* Create shell local variables from the values
7528 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007529 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007530 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007531 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007532 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007533 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007534 if (e) while (*e) {
7535 char *value = strchr(*e, '=');
7536 if (value) { /* paranoia */
7537 cur_var->next = xzalloc(sizeof(*cur_var));
7538 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007539 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007540 cur_var->max_len = strlen(*e);
7541 cur_var->flg_export = 1;
7542 }
7543 e++;
7544 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007545 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007546 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7547 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007548
7549 /* Export PWD */
7550 set_pwd_var(/*exp:*/ 1);
7551 /* bash also exports SHLVL and _,
7552 * and sets (but doesn't export) the following variables:
7553 * BASH=/bin/bash
7554 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7555 * BASH_VERSION='3.2.0(1)-release'
7556 * HOSTTYPE=i386
7557 * MACHTYPE=i386-pc-linux-gnu
7558 * OSTYPE=linux-gnu
7559 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007560 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007561 * EUID=<NNNNN>
7562 * UID=<NNNNN>
7563 * GROUPS=()
7564 * LINES=<NNN>
7565 * COLUMNS=<NNN>
7566 * BASH_ARGC=()
7567 * BASH_ARGV=()
7568 * BASH_LINENO=()
7569 * BASH_SOURCE=()
7570 * DIRSTACK=()
7571 * PIPESTATUS=([0]="0")
7572 * HISTFILE=/<xxx>/.bash_history
7573 * HISTFILESIZE=500
7574 * HISTSIZE=500
7575 * MAILCHECK=60
7576 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7577 * SHELL=/bin/bash
7578 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7579 * TERM=dumb
7580 * OPTERR=1
7581 * OPTIND=1
7582 * IFS=$' \t\n'
7583 * PS1='\s-\v\$ '
7584 * PS2='> '
7585 * PS4='+ '
7586 */
7587
Denis Vlasenko38f63192007-01-22 09:03:07 +00007588#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007589 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007590# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7591 {
7592 const char *hp = get_local_var_value("HISTFILE");
7593 if (!hp) {
7594 hp = get_local_var_value("HOME");
7595 if (hp) {
7596 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7597 //set_local_var(xasprintf("HISTFILE=%s", ...));
7598 }
7599 }
7600 }
7601# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007602#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007603
Denis Vlasenko87a86552008-07-29 19:43:10 +00007604 G.global_argc = argc;
7605 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007606 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007607 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007608
Denis Vlasenkoed782372009-04-10 00:45:02 +00007609 if (setjmp(die_jmp)) {
7610 /* xfunc has failed! die die die */
7611 /* no EXIT traps, this is an escape hatch! */
7612 G.exiting = 1;
7613 hush_exit(xfunc_error_retval);
7614 }
7615
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007616 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007617 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007618 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007619 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007620 * in order to intercept (more) signals.
7621 */
7622
7623 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007624 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007625 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007626 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007627 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007628#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007629 "<:$:R:V:"
7630# if ENABLE_HUSH_FUNCTIONS
7631 "F:"
7632# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007633#endif
7634 );
7635 if (opt <= 0)
7636 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007637 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007638 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007639 /* Possibilities:
7640 * sh ... -c 'script'
7641 * sh ... -c 'script' ARG0 [ARG1...]
7642 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007643 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007644 * "" needs to be replaced with NULL
7645 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007646 * Note: the form without ARG0 never happens:
7647 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007648 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007649 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007650 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007651 G.root_ppid = getppid();
7652 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007653 G.global_argv = argv + optind;
7654 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007655 if (builtin_argc) {
7656 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7657 const struct built_in_command *x;
7658
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007659 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007660 x = find_builtin(optarg);
7661 if (x) { /* paranoia */
7662 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7663 G.global_argv += builtin_argc;
7664 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007665 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007666 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007667 }
7668 goto final_return;
7669 }
7670 if (!G.global_argv[0]) {
7671 /* -c 'script' (no params): prevent empty $0 */
7672 G.global_argv--; /* points to argv[i] of 'script' */
7673 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007674 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007675 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007676 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007677 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007678 goto final_return;
7679 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007680 /* Well, we cannot just declare interactiveness,
7681 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007682 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007683 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007684 case 's':
7685 /* "-s" means "read from stdin", but this is how we always
7686 * operate, so simply do nothing here. */
7687 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007688#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007689 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007690 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007691 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007692 case '$': {
7693 unsigned long long empty_trap_mask;
7694
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007695 G.root_pid = bb_strtou(optarg, &optarg, 16);
7696 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007697 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7698 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007699 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7700 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007701 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007702 optarg++;
7703 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007704 optarg++;
7705 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7706 if (empty_trap_mask != 0) {
7707 int sig;
7708 init_sigmasks();
7709 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7710 for (sig = 1; sig < NSIG; sig++) {
7711 if (empty_trap_mask & (1LL << sig)) {
7712 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7713 sigaddset(&G.blocked_set, sig);
7714 }
7715 }
7716 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7717 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007718# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007719 optarg++;
7720 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007721# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007722 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007723 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007724 case 'R':
7725 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007726 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007727 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007728# if ENABLE_HUSH_FUNCTIONS
7729 case 'F': {
7730 struct function *funcp = new_function(optarg);
7731 /* funcp->name is already set to optarg */
7732 /* funcp->body is set to NULL. It's a special case. */
7733 funcp->body_as_string = argv[optind];
7734 optind++;
7735 break;
7736 }
7737# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007738#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007739 case 'n':
7740 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007741 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007742 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007743 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007744#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007745 fprintf(stderr, "Usage: sh [FILE]...\n"
7746 " or: sh -c command [args]...\n\n");
7747 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007748#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007749 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007750#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007751 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007752 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007753
Denys Vlasenkodea47882009-10-09 15:40:49 +02007754 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007755 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007756 G.root_ppid = getppid();
7757 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007758
7759 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007760 if (argv[0] && argv[0][0] == '-') {
7761 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007762 debug_printf("sourcing /etc/profile\n");
7763 input = fopen_for_read("/etc/profile");
7764 if (input != NULL) {
7765 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007766 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007767 parse_and_run_file(input);
7768 fclose(input);
7769 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007770 /* bash: after sourcing /etc/profile,
7771 * tries to source (in the given order):
7772 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007773 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007774 * bash also sources ~/.bash_logout on exit.
7775 * If called as sh, skips .bash_XXX files.
7776 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007777 }
7778
Denis Vlasenkof9375282009-04-05 19:13:39 +00007779 if (argv[optind]) {
7780 FILE *input;
7781 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007782 * "bash <script>" (which is never interactive (unless -i?))
7783 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007784 * If called as sh, does the same but with $ENV.
7785 */
7786 debug_printf("running script '%s'\n", argv[optind]);
7787 G.global_argv = argv + optind;
7788 G.global_argc = argc - optind;
7789 input = xfopen_for_read(argv[optind]);
7790 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007791 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007792 parse_and_run_file(input);
7793#if ENABLE_FEATURE_CLEAN_UP
7794 fclose(input);
7795#endif
7796 goto final_return;
7797 }
7798
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007799 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007800 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007801 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007802
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007803 /* A shell is interactive if the '-i' flag was given,
7804 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007805 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007806 * no arguments remaining or the -s flag given
7807 * standard input is a terminal
7808 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007809 * Refer to Posix.2, the description of the 'sh' utility.
7810 */
7811#if ENABLE_HUSH_JOB
7812 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007813 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7814 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7815 if (G_saved_tty_pgrp < 0)
7816 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007817
7818 /* try to dup stdin to high fd#, >= 255 */
7819 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7820 if (G_interactive_fd < 0) {
7821 /* try to dup to any fd */
7822 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007823 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007824 /* give up */
7825 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007826 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007827 }
7828 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007829// TODO: track & disallow any attempts of user
7830// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007831 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007832 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007833 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007834 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007835
Mike Frysinger38478a62009-05-20 04:48:06 -04007836 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007837 /* If we were run as 'hush &', sleep until we are
7838 * in the foreground (tty pgrp == our pgrp).
7839 * If we get started under a job aware app (like bash),
7840 * make sure we are now in charge so we don't fight over
7841 * who gets the foreground */
7842 while (1) {
7843 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007844 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7845 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007846 break;
7847 /* send TTIN to ourself (should stop us) */
7848 kill(- shell_pgrp, SIGTTIN);
7849 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007850 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007851
Denis Vlasenkof9375282009-04-05 19:13:39 +00007852 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007853 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007854
Mike Frysinger38478a62009-05-20 04:48:06 -04007855 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007856 /* Set other signals to restore saved_tty_pgrp */
7857 set_fatal_handlers();
7858 /* Put ourselves in our own process group
7859 * (bash, too, does this only if ctty is available) */
7860 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7861 /* Grab control of the terminal */
7862 tcsetpgrp(G_interactive_fd, getpid());
7863 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007864 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007865 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007866 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007867 } else {
7868 init_sigmasks();
7869 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007870#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007871 /* No job control compiled in, only prompt/line editing */
7872 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007873 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7874 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007875 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007876 G_interactive_fd = dup(STDIN_FILENO);
7877 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007878 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007879 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007880 }
7881 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007882 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007883 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007884 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007885 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007886#else
7887 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007888 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007889#endif
7890 /* bash:
7891 * if interactive but not a login shell, sources ~/.bashrc
7892 * (--norc turns this off, --rcfile <file> overrides)
7893 */
7894
7895 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007896 /* note: ash and hush share this string */
7897 printf("\n\n%s %s\n"
7898 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7899 "\n",
7900 bb_banner,
7901 "hush - the humble shell"
7902 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007903 }
7904
Denis Vlasenkof9375282009-04-05 19:13:39 +00007905 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007906
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007907 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007908 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007909}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007910
7911
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007912#if ENABLE_MSH
7913int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7914int msh_main(int argc, char **argv)
7915{
7916 //bb_error_msg("msh is deprecated, please use hush instead");
7917 return hush_main(argc, argv);
7918}
7919#endif
7920
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007921
7922/*
7923 * Built-ins
7924 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007925static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007926{
7927 return 0;
7928}
7929
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007930static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007931{
7932 int argc = 0;
7933 while (*argv) {
7934 argc++;
7935 argv++;
7936 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007937 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007938}
7939
7940static int FAST_FUNC builtin_test(char **argv)
7941{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007942 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007943}
7944
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007945static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007946{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007947 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007948}
7949
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007950#if ENABLE_PRINTF
7951static int FAST_FUNC builtin_printf(char **argv)
7952{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007953 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007954}
7955#endif
7956
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007957static char **skip_dash_dash(char **argv)
7958{
7959 argv++;
7960 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7961 argv++;
7962 return argv;
7963}
7964
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007965static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007966{
7967 int rcode = EXIT_SUCCESS;
7968
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007969 argv = skip_dash_dash(argv);
7970 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007971 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007972 /* bash:
7973 * eval "echo Hi; done" ("done" is syntax error):
7974 * "echo Hi" will not execute too.
7975 */
7976 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007977 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007978 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007979 }
7980 return rcode;
7981}
7982
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007983static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007984{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007985 const char *newdir;
7986
7987 argv = skip_dash_dash(argv);
7988 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007989 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007990 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007991 * bash says "bash: cd: HOME not set" and does nothing
7992 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007993 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007994 const char *home = get_local_var_value("HOME");
7995 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007996 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007997 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007998 /* Mimic bash message exactly */
7999 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008000 return EXIT_FAILURE;
8001 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008002 /* Read current dir (get_cwd(1) is inside) and set PWD.
8003 * Note: do not enforce exporting. If PWD was unset or unexported,
8004 * set it again, but do not export. bash does the same.
8005 */
8006 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008007 return EXIT_SUCCESS;
8008}
8009
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008010static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008011{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008012 argv = skip_dash_dash(argv);
8013 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008014 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008015
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008016 /* Careful: we can end up here after [v]fork. Do not restore
8017 * tty pgrp then, only top-level shell process does that */
8018 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8019 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8020
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008021 /* TODO: if exec fails, bash does NOT exit! We do.
8022 * We'll need to undo sigprocmask (it's inside execvp_or_die)
8023 * and tcsetpgrp, and this is inherently racy.
8024 */
8025 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008026}
8027
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008028static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008029{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008030 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008031
8032 /* interactive bash:
8033 * # trap "echo EEE" EXIT
8034 * # exit
8035 * exit
8036 * There are stopped jobs.
8037 * (if there are _stopped_ jobs, running ones don't count)
8038 * # exit
8039 * exit
8040 # EEE (then bash exits)
8041 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008042 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008043 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008044
8045 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008046 argv = skip_dash_dash(argv);
8047 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008048 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008049 /* mimic bash: exit 123abc == exit 255 + error msg */
8050 xfunc_error_retval = 255;
8051 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008052 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008053}
8054
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008055static void print_escaped(const char *s)
8056{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008057 if (*s == '\'')
8058 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008059 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008060 const char *p = strchrnul(s, '\'');
8061 /* print 'xxxx', possibly just '' */
8062 printf("'%.*s'", (int)(p - s), s);
8063 if (*p == '\0')
8064 break;
8065 s = p;
8066 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008067 /* s points to '; print "'''...'''" */
8068 putchar('"');
8069 do putchar('\''); while (*++s == '\'');
8070 putchar('"');
8071 } while (*s);
8072}
8073
Denys Vlasenko295fef82009-06-03 12:47:26 +02008074#if !ENABLE_HUSH_LOCAL
8075#define helper_export_local(argv, exp, lvl) \
8076 helper_export_local(argv, exp)
8077#endif
8078static void helper_export_local(char **argv, int exp, int lvl)
8079{
8080 do {
8081 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008082 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008083
8084 /* So far we do not check that name is valid (TODO?) */
8085
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008086 if (*name_end == '\0') {
8087 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008088
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008089 vpp = get_ptr_to_local_var(name, name_end - name);
8090 var = vpp ? *vpp : NULL;
8091
Denys Vlasenko295fef82009-06-03 12:47:26 +02008092 if (exp == -1) { /* unexporting? */
8093 /* export -n NAME (without =VALUE) */
8094 if (var) {
8095 var->flg_export = 0;
8096 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8097 unsetenv(name);
8098 } /* else: export -n NOT_EXISTING_VAR: no-op */
8099 continue;
8100 }
8101 if (exp == 1) { /* exporting? */
8102 /* export NAME (without =VALUE) */
8103 if (var) {
8104 var->flg_export = 1;
8105 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8106 putenv(var->varstr);
8107 continue;
8108 }
8109 }
8110 /* Exporting non-existing variable.
8111 * bash does not put it in environment,
8112 * but remembers that it is exported,
8113 * and does put it in env when it is set later.
8114 * We just set it to "" and export. */
8115 /* Or, it's "local NAME" (without =VALUE).
8116 * bash sets the value to "". */
8117 name = xasprintf("%s=", name);
8118 } else {
8119 /* (Un)exporting/making local NAME=VALUE */
8120 name = xstrdup(name);
8121 }
8122 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8123 } while (*++argv);
8124}
8125
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008126static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008127{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008128 unsigned opt_unexport;
8129
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008130#if ENABLE_HUSH_EXPORT_N
8131 /* "!": do not abort on errors */
8132 opt_unexport = getopt32(argv, "!n");
8133 if (opt_unexport == (uint32_t)-1)
8134 return EXIT_FAILURE;
8135 argv += optind;
8136#else
8137 opt_unexport = 0;
8138 argv++;
8139#endif
8140
8141 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008142 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008143 if (e) {
8144 while (*e) {
8145#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008146 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008147#else
8148 /* ash emits: export VAR='VAL'
8149 * bash: declare -x VAR="VAL"
8150 * we follow ash example */
8151 const char *s = *e++;
8152 const char *p = strchr(s, '=');
8153
8154 if (!p) /* wtf? take next variable */
8155 continue;
8156 /* export var= */
8157 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008158 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008159 putchar('\n');
8160#endif
8161 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008162 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008163 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008164 return EXIT_SUCCESS;
8165 }
8166
Denys Vlasenko295fef82009-06-03 12:47:26 +02008167 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008168
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008169 return EXIT_SUCCESS;
8170}
8171
Denys Vlasenko295fef82009-06-03 12:47:26 +02008172#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008173static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008174{
8175 if (G.func_nest_level == 0) {
8176 bb_error_msg("%s: not in a function", argv[0]);
8177 return EXIT_FAILURE; /* bash compat */
8178 }
8179 helper_export_local(argv, 0, G.func_nest_level);
8180 return EXIT_SUCCESS;
8181}
8182#endif
8183
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008184static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008185{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008186 int sig;
8187 char *new_cmd;
8188
8189 if (!G.traps)
8190 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8191
8192 argv++;
8193 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008194 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008195 /* No args: print all trapped */
8196 for (i = 0; i < NSIG; ++i) {
8197 if (G.traps[i]) {
8198 printf("trap -- ");
8199 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008200 /* note: bash adds "SIG", but only if invoked
8201 * as "bash". If called as "sh", or if set -o posix,
8202 * then it prints short signal names.
8203 * We are printing short names: */
8204 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008205 }
8206 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008207 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008208 return EXIT_SUCCESS;
8209 }
8210
8211 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008212 /* If first arg is a number: reset all specified signals */
8213 sig = bb_strtou(*argv, NULL, 10);
8214 if (errno == 0) {
8215 int ret;
8216 process_sig_list:
8217 ret = EXIT_SUCCESS;
8218 while (*argv) {
8219 sig = get_signum(*argv++);
8220 if (sig < 0 || sig >= NSIG) {
8221 ret = EXIT_FAILURE;
8222 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008223 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008224 continue;
8225 }
8226
8227 free(G.traps[sig]);
8228 G.traps[sig] = xstrdup(new_cmd);
8229
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008230 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008231 get_signame(sig), sig, G.traps[sig]);
8232
8233 /* There is no signal for 0 (EXIT) */
8234 if (sig == 0)
8235 continue;
8236
8237 if (new_cmd) {
8238 sigaddset(&G.blocked_set, sig);
8239 } else {
8240 /* There was a trap handler, we are removing it
8241 * (if sig has non-DFL handling,
8242 * we don't need to do anything) */
8243 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8244 continue;
8245 sigdelset(&G.blocked_set, sig);
8246 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008247 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008248 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008249 return ret;
8250 }
8251
8252 if (!argv[1]) { /* no second arg */
8253 bb_error_msg("trap: invalid arguments");
8254 return EXIT_FAILURE;
8255 }
8256
8257 /* First arg is "-": reset all specified to default */
8258 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8259 /* Everything else: set arg as signal handler
8260 * (includes "" case, which ignores signal) */
8261 if (argv[0][0] == '-') {
8262 if (argv[0][1] == '\0') { /* "-" */
8263 /* new_cmd remains NULL: "reset these sigs" */
8264 goto reset_traps;
8265 }
8266 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8267 argv++;
8268 }
8269 /* else: "-something", no special meaning */
8270 }
8271 new_cmd = *argv;
8272 reset_traps:
8273 argv++;
8274 goto process_sig_list;
8275}
8276
Mike Frysinger93cadc22009-05-27 17:06:25 -04008277/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008278static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008279{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008280 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008281
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008282 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008283 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008284 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008285
8286 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008287 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008288 type = "an alias";*/
8289#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008290 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008291 type = "a function";
8292#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008293 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008294 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008295 else if ((path = find_in_path(*argv)) != NULL)
8296 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008297 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008298 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008299 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008300 continue;
8301 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008302
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008303 printf("%s is %s\n", *argv, type);
8304 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008305 }
8306
8307 return ret;
8308}
8309
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008310#if ENABLE_HUSH_JOB
8311/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008312static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008313{
8314 int i, jobnum;
8315 struct pipe *pi;
8316
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008317 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008318 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008319
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008320 /* If they gave us no args, assume they want the last backgrounded task */
8321 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008322 for (pi = G.job_list; pi; pi = pi->next) {
8323 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008324 goto found;
8325 }
8326 }
8327 bb_error_msg("%s: no current job", argv[0]);
8328 return EXIT_FAILURE;
8329 }
8330 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8331 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8332 return EXIT_FAILURE;
8333 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008334 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008335 if (pi->jobid == jobnum) {
8336 goto found;
8337 }
8338 }
8339 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8340 return EXIT_FAILURE;
8341 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008342 /* TODO: bash prints a string representation
8343 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008344 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008345 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008346 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008347 }
8348
8349 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008350 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8351 for (i = 0; i < pi->num_cmds; i++) {
8352 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8353 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008354 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008355 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008356
8357 i = kill(- pi->pgrp, SIGCONT);
8358 if (i < 0) {
8359 if (errno == ESRCH) {
8360 delete_finished_bg_job(pi);
8361 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008362 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008363 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008364 }
8365
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008366 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008367 remove_bg_job(pi);
8368 return checkjobs_and_fg_shell(pi);
8369 }
8370 return EXIT_SUCCESS;
8371}
8372#endif
8373
8374#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008375static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008376{
8377 const struct built_in_command *x;
8378
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008379 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008380 "Built-in commands:\n"
8381 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008382 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008383 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008384 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008385 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008386 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008387 return EXIT_SUCCESS;
8388}
8389#endif
8390
8391#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008392static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008393{
8394 struct pipe *job;
8395 const char *status_string;
8396
Denis Vlasenko87a86552008-07-29 19:43:10 +00008397 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008398 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008399 status_string = "Stopped";
8400 else
8401 status_string = "Running";
8402
8403 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8404 }
8405 return EXIT_SUCCESS;
8406}
8407#endif
8408
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008409#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008410static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008411{
8412 void *p;
8413 unsigned long l;
8414
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008415# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008416 /* Optional. Reduces probability of false positives */
8417 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008418# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008419 /* Crude attempt to find where "free memory" starts,
8420 * sans fragmentation. */
8421 p = malloc(240);
8422 l = (unsigned long)p;
8423 free(p);
8424 p = malloc(3400);
8425 if (l < (unsigned long)p) l = (unsigned long)p;
8426 free(p);
8427
8428 if (!G.memleak_value)
8429 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008430
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008431 l -= G.memleak_value;
8432 if ((long)l < 0)
8433 l = 0;
8434 l /= 1024;
8435 if (l > 127)
8436 l = 127;
8437
8438 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8439 return l;
8440}
8441#endif
8442
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008443static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008444{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008445 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008446 return EXIT_SUCCESS;
8447}
8448
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008449static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008450{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008451 const char *r;
8452 char *opt_n = NULL;
8453 char *opt_p = NULL;
8454 char *opt_t = NULL;
8455 char *opt_u = NULL;
8456 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008457
Denys Vlasenko03dad222010-01-12 23:29:57 +01008458 /* "!": do not abort on errors.
8459 * Option string must start with "sr" to match BUILTIN_READ_xxx
8460 */
8461 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8462 if (read_flags == (uint32_t)-1)
8463 return EXIT_FAILURE;
8464 argv += optind;
8465
8466 r = shell_builtin_read(set_local_var_from_halves,
8467 argv,
8468 get_local_var_value("IFS"), /* can be NULL */
8469 read_flags,
8470 opt_n,
8471 opt_p,
8472 opt_t,
8473 opt_u
8474 );
8475
8476 if ((uintptr_t)r > 1) {
8477 bb_error_msg("%s", r);
8478 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008479 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008480
Denys Vlasenko03dad222010-01-12 23:29:57 +01008481 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008482}
8483
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008484/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8485 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008486 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008487 * set [-abCefhmnuvx] [-o option] [argument...]
8488 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008489 * set -- [argument...]
8490 * set -o
8491 * set +o
8492 * Implementations shall support the options in both their hyphen and
8493 * plus-sign forms. These options can also be specified as options to sh.
8494 * Examples:
8495 * Write out all variables and their values: set
8496 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8497 * Turn on the -x and -v options: set -xv
8498 * Unset all positional parameters: set --
8499 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8500 * Set the positional parameters to the expansion of x, even if x expands
8501 * with a leading '-' or '+': set -- $x
8502 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008503 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008504 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008505static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008506{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008507 int n;
8508 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008509 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008510
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008511 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008512 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008513 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008514 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008515 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008516 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008517
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008518 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008519 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008520 ++argv;
8521 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008522 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008523 if (arg[0] != '+' && arg[0] != '-')
8524 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008525 for (n = 1; arg[n]; ++n) {
8526 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008527 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008528 if (arg[n] == 'o' && argv[1])
8529 argv++;
8530 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008531 } while ((arg = *++argv) != NULL);
8532 /* Now argv[0] is 1st argument */
8533
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008534 if (arg == NULL)
8535 return EXIT_SUCCESS;
8536 set_argv:
8537
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008538 /* NB: G.global_argv[0] ($0) is never freed/changed */
8539 g_argv = G.global_argv;
8540 if (G.global_args_malloced) {
8541 pp = g_argv;
8542 while (*++pp)
8543 free(*pp);
8544 g_argv[1] = NULL;
8545 } else {
8546 G.global_args_malloced = 1;
8547 pp = xzalloc(sizeof(pp[0]) * 2);
8548 pp[0] = g_argv[0]; /* retain $0 */
8549 g_argv = pp;
8550 }
8551 /* This realloc's G.global_argv */
8552 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8553
8554 n = 1;
8555 while (*++pp)
8556 n++;
8557 G.global_argc = n;
8558
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008559 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008560
8561 /* Nothing known, so abort */
8562 error:
8563 bb_error_msg("set: %s: invalid option", arg);
8564 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008565}
8566
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008567static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008568{
8569 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008570 argv = skip_dash_dash(argv);
8571 if (argv[0]) {
8572 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008573 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008574 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008575 if (G.global_args_malloced) {
8576 int m = 1;
8577 while (m <= n)
8578 free(G.global_argv[m++]);
8579 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008580 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008581 memmove(&G.global_argv[1], &G.global_argv[n+1],
8582 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008583 return EXIT_SUCCESS;
8584 }
8585 return EXIT_FAILURE;
8586}
8587
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008588static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008589{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008590 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008591 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008592 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008593#if ENABLE_HUSH_FUNCTIONS
8594 smallint sv_flg;
8595#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008596
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008597 argv = skip_dash_dash(argv);
8598 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008599 if (!filename) {
8600 /* bash says: "bash: .: filename argument required" */
8601 return 2; /* bash compat */
8602 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008603 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008604 if (!strchr(filename, '/')) {
8605 arg_path = find_in_path(filename);
8606 if (arg_path)
8607 filename = arg_path;
8608 }
8609 input = fopen_or_warn(filename, "r");
8610 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008611 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008612 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008613 return EXIT_FAILURE;
8614 }
8615 close_on_exec_on(fileno(input));
8616
Mike Frysinger885b6f22009-04-18 21:04:25 +00008617#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008618 sv_flg = G.flag_return_in_progress;
8619 /* "we are inside sourced file, ok to use return" */
8620 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008621#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008622 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008623
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008624 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008625 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008626
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008627 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008628#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008629 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008630#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008631
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008632 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008633}
8634
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008635static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008636{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008637 int rc;
8638 mode_t mask;
8639
8640 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008641 argv = skip_dash_dash(argv);
8642 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008643 mode_t old_mask = mask;
8644
8645 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008646 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008647 mask ^= 0777;
8648 if (rc == 0) {
8649 mask = old_mask;
8650 /* bash messages:
8651 * bash: umask: 'q': invalid symbolic mode operator
8652 * bash: umask: 999: octal number out of range
8653 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008654 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008655 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008656 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008657 rc = 1;
8658 /* Mimic bash */
8659 printf("%04o\n", (unsigned) mask);
8660 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008661 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008662 umask(mask);
8663
8664 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008665}
8666
Mike Frysingerd690f682009-03-30 06:50:54 +00008667/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008668static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008669{
Mike Frysingerd690f682009-03-30 06:50:54 +00008670 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008671 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008672
Denis Vlasenko28e67962009-04-26 23:22:40 +00008673 /* "!": do not abort on errors */
8674 /* "+": stop at 1st non-option */
8675 opts = getopt32(argv, "!+vf");
8676 if (opts == (unsigned)-1)
8677 return EXIT_FAILURE;
8678 if (opts == 3) {
8679 bb_error_msg("unset: -v and -f are exclusive");
8680 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008681 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008682 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008683
8684 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008685 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008686 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008687 if (unset_local_var(*argv)) {
8688 /* unset <nonexistent_var> doesn't fail.
8689 * Error is when one tries to unset RO var.
8690 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008691 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008692 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008693 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008694#if ENABLE_HUSH_FUNCTIONS
8695 else {
8696 unset_func(*argv);
8697 }
8698#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008699 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008700 }
8701 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008702}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008703
Mike Frysinger56bdea12009-03-28 20:01:58 +00008704/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008705static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008706{
8707 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008708 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008709
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008710 argv = skip_dash_dash(argv);
8711 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008712 /* Don't care about wait results */
8713 /* Note 1: must wait until there are no more children */
8714 /* Note 2: must be interruptible */
8715 /* Examples:
8716 * $ sleep 3 & sleep 6 & wait
8717 * [1] 30934 sleep 3
8718 * [2] 30935 sleep 6
8719 * [1] Done sleep 3
8720 * [2] Done sleep 6
8721 * $ sleep 3 & sleep 6 & wait
8722 * [1] 30936 sleep 3
8723 * [2] 30937 sleep 6
8724 * [1] Done sleep 3
8725 * ^C <-- after ~4 sec from keyboard
8726 * $
8727 */
8728 sigaddset(&G.blocked_set, SIGCHLD);
8729 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8730 while (1) {
8731 checkjobs(NULL);
8732 if (errno == ECHILD)
8733 break;
8734 /* Wait for SIGCHLD or any other signal of interest */
8735 /* sigtimedwait with infinite timeout: */
8736 sig = sigwaitinfo(&G.blocked_set, NULL);
8737 if (sig > 0) {
8738 sig = check_and_run_traps(sig);
8739 if (sig && sig != SIGCHLD) { /* see note 2 */
8740 ret = 128 + sig;
8741 break;
8742 }
8743 }
8744 }
8745 sigdelset(&G.blocked_set, SIGCHLD);
8746 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8747 return ret;
8748 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008749
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008750 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008751 while (*argv) {
8752 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008753 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008754 /* mimic bash message */
8755 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008756 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008757 }
8758 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008759 if (WIFSIGNALED(status))
8760 ret = 128 + WTERMSIG(status);
8761 else if (WIFEXITED(status))
8762 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008763 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008764 ret = EXIT_FAILURE;
8765 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008766 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008767 ret = 127;
8768 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008769 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008770 }
8771
8772 return ret;
8773}
8774
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008775#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8776static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8777{
8778 if (argv[1]) {
8779 def = bb_strtou(argv[1], NULL, 10);
8780 if (errno || def < def_min || argv[2]) {
8781 bb_error_msg("%s: bad arguments", argv[0]);
8782 def = UINT_MAX;
8783 }
8784 }
8785 return def;
8786}
8787#endif
8788
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008789#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008790static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008791{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008792 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008793 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008794 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008795 return EXIT_SUCCESS; /* bash compat */
8796 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008797 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008798
8799 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8800 if (depth == UINT_MAX)
8801 G.flag_break_continue = BC_BREAK;
8802 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008803 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008804
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008805 return EXIT_SUCCESS;
8806}
8807
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008808static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008809{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008810 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8811 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008812}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008813#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008814
8815#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008816static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008817{
8818 int rc;
8819
8820 if (G.flag_return_in_progress != -1) {
8821 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8822 return EXIT_FAILURE; /* bash compat */
8823 }
8824
8825 G.flag_return_in_progress = 1;
8826
8827 /* bash:
8828 * out of range: wraps around at 256, does not error out
8829 * non-numeric param:
8830 * f() { false; return qwe; }; f; echo $?
8831 * bash: return: qwe: numeric argument required <== we do this
8832 * 255 <== we also do this
8833 */
8834 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8835 return rc;
8836}
8837#endif