blob: e4c3a7d774e1501af192250342281397e02952a7 [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 Vlasenkod68ae082009-04-09 20:41:34 +00001098static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001099{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001100 char msg[2] = { ch, '\0' };
1101 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001102}
1103
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001104static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001105{
1106 char msg[2];
1107 msg[0] = ch;
1108 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001109 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001110}
1111
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112#if HUSH_DEBUG < 2
1113# undef die_if_script
1114# undef syntax_error
1115# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001116# undef syntax_error_unterm_ch
1117# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001118# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001119#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001120# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001121# define syntax_error(msg) syntax_error(__LINE__, msg)
1122# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1123# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1124# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1125# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001126#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001127
Denis Vlasenko552433b2009-04-04 19:29:21 +00001128
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001129#if ENABLE_HUSH_INTERACTIVE
1130static void cmdedit_update_prompt(void);
1131#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001132# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001133#endif
1134
1135
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001136/* Utility functions
1137 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001138/* Replace each \x with x in place, return ptr past NUL. */
1139static char *unbackslash(char *src)
1140{
Denys Vlasenko71885402009-09-24 01:44:13 +02001141 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001142 while (1) {
1143 if (*src == '\\')
1144 src++;
1145 if ((*dst++ = *src++) == '\0')
1146 break;
1147 }
1148 return dst;
1149}
1150
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001151static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001152{
1153 int i;
1154 unsigned count1;
1155 unsigned count2;
1156 char **v;
1157
1158 v = strings;
1159 count1 = 0;
1160 if (v) {
1161 while (*v) {
1162 count1++;
1163 v++;
1164 }
1165 }
1166 count2 = 0;
1167 v = add;
1168 while (*v) {
1169 count2++;
1170 v++;
1171 }
1172 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1173 v[count1 + count2] = NULL;
1174 i = count2;
1175 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001176 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001177 return v;
1178}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001179#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001180static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1181{
1182 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1183 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1184 return ptr;
1185}
1186#define add_strings_to_strings(strings, add, need_to_dup) \
1187 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1188#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001189
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001190/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001191static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001192{
1193 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001194 v[0] = add;
1195 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001196 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001197}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001198#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001199static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1200{
1201 char **ptr = add_string_to_strings(strings, add);
1202 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1203 return ptr;
1204}
1205#define add_string_to_strings(strings, add) \
1206 xx_add_string_to_strings(__LINE__, strings, add)
1207#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001208
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001209static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001210{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001211 char **v;
1212
1213 if (!strings)
1214 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001215 v = strings;
1216 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001217 free(*v);
1218 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001219 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001220 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001221}
1222
Denis Vlasenko76d50412008-06-10 16:19:39 +00001223
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001224/* Helpers for setting new $n and restoring them back
1225 */
1226typedef struct save_arg_t {
1227 char *sv_argv0;
1228 char **sv_g_argv;
1229 int sv_g_argc;
1230 smallint sv_g_malloced;
1231} save_arg_t;
1232
1233static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1234{
1235 int n;
1236
1237 sv->sv_argv0 = argv[0];
1238 sv->sv_g_argv = G.global_argv;
1239 sv->sv_g_argc = G.global_argc;
1240 sv->sv_g_malloced = G.global_args_malloced;
1241
1242 argv[0] = G.global_argv[0]; /* retain $0 */
1243 G.global_argv = argv;
1244 G.global_args_malloced = 0;
1245
1246 n = 1;
1247 while (*++argv)
1248 n++;
1249 G.global_argc = n;
1250}
1251
1252static void restore_G_args(save_arg_t *sv, char **argv)
1253{
1254 char **pp;
1255
1256 if (G.global_args_malloced) {
1257 /* someone ran "set -- arg1 arg2 ...", undo */
1258 pp = G.global_argv;
1259 while (*++pp) /* note: does not free $0 */
1260 free(*pp);
1261 free(G.global_argv);
1262 }
1263 argv[0] = sv->sv_argv0;
1264 G.global_argv = sv->sv_g_argv;
1265 G.global_argc = sv->sv_g_argc;
1266 G.global_args_malloced = sv->sv_g_malloced;
1267}
1268
1269
Denis Vlasenkod5762932009-03-31 11:22:57 +00001270/* Basic theory of signal handling in shell
1271 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001272 * This does not describe what hush does, rather, it is current understanding
1273 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001274 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1275 *
1276 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1277 * is finished or backgrounded. It is the same in interactive and
1278 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001279 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001280 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001281 * backgrounds (i.e. stops) or kills all members of currently running
1282 * pipe.
1283 *
1284 * Wait builtin in interruptible by signals for which user trap is set
1285 * or by SIGINT in interactive shell.
1286 *
1287 * Trap handlers will execute even within trap handlers. (right?)
1288 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001289 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1290 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001291 *
1292 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001293 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001294 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001295 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001296 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001297 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001298 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001299 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001300 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001301 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001302 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001303 *
1304 * SIGQUIT: ignore
1305 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001306 * SIGHUP (interactive):
1307 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001308 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001309 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1310 * that all pipe members are stopped. Try this in bash:
1311 * while :; do :; done - ^Z does not background it
1312 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001313 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001314 * of the command line, show prompt. NB: ^C does not send SIGINT
1315 * to interactive shell while shell is waiting for a pipe,
1316 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001317 * Example 1: this waits 5 sec, but does not execute ls:
1318 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1319 * Example 2: this does not wait and does not execute ls:
1320 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1321 * Example 3: this does not wait 5 sec, but executes ls:
1322 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001323 *
1324 * (What happens to signals which are IGN on shell start?)
1325 * (What happens with signal mask on shell start?)
1326 *
1327 * Implementation in hush
1328 * ======================
1329 * We use in-kernel pending signal mask to determine which signals were sent.
1330 * We block all signals which we don't want to take action immediately,
1331 * i.e. we block all signals which need to have special handling as described
1332 * above, and all signals which have traps set.
1333 * After each pipe execution, we extract any pending signals via sigtimedwait()
1334 * and act on them.
1335 *
1336 * unsigned non_DFL_mask: a mask of such "special" signals
1337 * sigset_t blocked_set: current blocked signal set
1338 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001339 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001340 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001341 * "trap 'cmd' SIGxxx":
1342 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001343 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001344 * unblock signals with special interactive handling
1345 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001346 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001347 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001348 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001349 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001350 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001351 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001352 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001353 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001354 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001355 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001356 * Standard says "When a subshell is entered, traps that are not being ignored
1357 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001358 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001359 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001360enum {
1361 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001362 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001363 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001364 | (1 << SIGHUP)
1365 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001366 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001367#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001368 | (1 << SIGTTIN)
1369 | (1 << SIGTTOU)
1370 | (1 << SIGTSTP)
1371#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001372};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001373
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001374#if ENABLE_HUSH_FAST
1375static void SIGCHLD_handler(int sig UNUSED_PARAM)
1376{
1377 G.count_SIGCHLD++;
1378//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1379}
1380#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001381
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001382#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001383
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001384/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001385# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001386/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001387# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001388
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001389/* Restores tty foreground process group, and exits.
1390 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001391 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001392 * or called directly with -EXITCODE.
1393 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001394static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001395static void sigexit(int sig)
1396{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001397 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001398 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001399
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001400 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001401 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001402 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1403 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001404
1405 /* Not a signal, just exit */
1406 if (sig <= 0)
1407 _exit(- sig);
1408
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001409 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001410}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001411#else
1412
Denys Vlasenko8391c482010-05-22 17:50:43 +02001413# define disable_restore_tty_pgrp_on_exit() ((void)0)
1414# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001415
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001416#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001417
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001418/* Restores tty foreground process group, and exits. */
1419static void hush_exit(int exitcode) NORETURN;
1420static void hush_exit(int exitcode)
1421{
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001422 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001423 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1424 /* Prevent recursion:
1425 * trap "echo Hi; exit" EXIT; exit
1426 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001427 char *argv[3];
1428 /* argv[0] is unused */
1429 argv[1] = G.traps[0];
1430 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001431 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001432 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001433 * "trap" will still show it, if executed
1434 * in the handler */
1435 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001436 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001437
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001438#if ENABLE_FEATURE_CLEAN_UP
1439 {
1440 struct variable *cur_var;
1441 if (G.cwd != bb_msg_unknown)
1442 free((char*)G.cwd);
1443 cur_var = G.top_var;
1444 while (cur_var) {
1445 struct variable *tmp = cur_var;
1446 if (!cur_var->max_len)
1447 free(cur_var->varstr);
1448 cur_var = cur_var->next;
1449 free(tmp);
1450 }
1451 }
1452#endif
1453
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001454#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001455 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001456 sigexit(- (exitcode & 0xff));
1457#else
1458 exit(exitcode);
1459#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001460}
1461
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001462
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001463static int check_and_run_traps(int sig)
1464{
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001465 /* I want it in rodata, not in bss.
1466 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1467 * initializer. But other compilers may still use bss.
1468 * TODO: find more portable solution.
1469 */
1470 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001471 smalluint save_rcode;
1472 int last_sig = 0;
1473
1474 if (sig)
1475 goto jump_in;
1476 while (1) {
1477 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1478 if (sig <= 0)
1479 break;
1480 jump_in:
1481 last_sig = sig;
1482 if (G.traps && G.traps[sig]) {
1483 if (G.traps[sig][0]) {
1484 /* We have user-defined handler */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001485 char *argv[3];
1486 /* argv[0] is unused */
1487 argv[1] = G.traps[sig];
1488 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001489 save_rcode = G.last_exitcode;
1490 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001491 G.last_exitcode = save_rcode;
1492 } /* else: "" trap, ignoring signal */
1493 continue;
1494 }
1495 /* not a trap: special action */
1496 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001497#if ENABLE_HUSH_FAST
1498 case SIGCHLD:
1499 G.count_SIGCHLD++;
1500//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1501 break;
1502#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001503 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001504 /* Builtin was ^C'ed, make it look prettier: */
1505 bb_putchar('\n');
1506 G.flag_SIGINT = 1;
1507 break;
1508#if ENABLE_HUSH_JOB
1509 case SIGHUP: {
1510 struct pipe *job;
1511 /* bash is observed to signal whole process groups,
1512 * not individual processes */
1513 for (job = G.job_list; job; job = job->next) {
1514 if (job->pgrp <= 0)
1515 continue;
1516 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1517 if (kill(- job->pgrp, SIGHUP) == 0)
1518 kill(- job->pgrp, SIGCONT);
1519 }
1520 sigexit(SIGHUP);
1521 }
1522#endif
1523 default: /* ignored: */
1524 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1525 break;
1526 }
1527 }
1528 return last_sig;
1529}
1530
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001531
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001532static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001533{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001534 if (force || G.cwd == NULL) {
1535 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1536 * we must not try to free(bb_msg_unknown) */
1537 if (G.cwd == bb_msg_unknown)
1538 G.cwd = NULL;
1539 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1540 if (!G.cwd)
1541 G.cwd = bb_msg_unknown;
1542 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001543 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001544}
1545
Denis Vlasenko83506862007-11-23 13:11:42 +00001546
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001547/*
1548 * Shell and environment variable support
1549 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001550static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001551{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001552 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001553 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001554
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001555 pp = &G.top_var;
1556 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001557 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001558 return pp;
1559 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001560 }
1561 return NULL;
1562}
1563
Denys Vlasenko03dad222010-01-12 23:29:57 +01001564static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001565{
Denys Vlasenko29082232010-07-16 13:52:32 +02001566 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001567 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001568
1569 if (G.expanded_assignments) {
1570 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001571 while (*cpp) {
1572 char *cp = *cpp;
1573 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1574 return cp + len + 1;
1575 cpp++;
1576 }
1577 }
1578
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001579 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001580 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001581 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001582
Denys Vlasenkodea47882009-10-09 15:40:49 +02001583 if (strcmp(name, "PPID") == 0)
1584 return utoa(G.root_ppid);
1585 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001586#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001587 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001588 return utoa(next_random(&G.random_gen));
1589#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001590 return NULL;
1591}
1592
1593/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001594 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001595 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001596 * 0: do not change export flag
1597 * (if creating new variable, flag will be 0)
1598 * 1: set export flag and putenv the variable
1599 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001600 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001601 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001602#if !BB_MMU && ENABLE_HUSH_LOCAL
1603/* all params are used */
1604#elif BB_MMU && ENABLE_HUSH_LOCAL
1605#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1606 set_local_var(str, flg_export, local_lvl)
1607#elif BB_MMU && !ENABLE_HUSH_LOCAL
1608#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001609 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001610#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1611#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1612 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001613#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001614static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001615{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001616 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001617 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001618 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001619 int name_len;
1620
Denis Vlasenko950bd722009-04-21 11:23:56 +00001621 eq_sign = strchr(str, '=');
1622 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001623 free(str);
1624 return -1;
1625 }
1626
Denis Vlasenko950bd722009-04-21 11:23:56 +00001627 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001628 var_pp = &G.top_var;
1629 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001630 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001631 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001632 continue;
1633 }
1634 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001635 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001636#if !BB_MMU
1637 if (!flg_read_only)
1638#endif
1639 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001640 free(str);
1641 return -1;
1642 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001643 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001644 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1645 *eq_sign = '\0';
1646 unsetenv(str);
1647 *eq_sign = '=';
1648 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001649#if ENABLE_HUSH_LOCAL
1650 if (cur->func_nest_level < local_lvl) {
1651 /* New variable is declared as local,
1652 * and existing one is global, or local
1653 * from enclosing function.
1654 * Remove and save old one: */
1655 *var_pp = cur->next;
1656 cur->next = *G.shadowed_vars_pp;
1657 *G.shadowed_vars_pp = cur;
1658 /* bash 3.2.33(1) and exported vars:
1659 * # export z=z
1660 * # f() { local z=a; env | grep ^z; }
1661 * # f
1662 * z=a
1663 * # env | grep ^z
1664 * z=z
1665 */
1666 if (cur->flg_export)
1667 flg_export = 1;
1668 break;
1669 }
1670#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001671 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001672 free_and_exp:
1673 free(str);
1674 goto exp;
1675 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001676 if (cur->max_len != 0) {
1677 if (cur->max_len >= strlen(str)) {
1678 /* This one is from startup env, reuse space */
1679 strcpy(cur->varstr, str);
1680 goto free_and_exp;
1681 }
1682 } else {
1683 /* max_len == 0 signifies "malloced" var, which we can
1684 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001685 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001686 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001687 cur->max_len = 0;
1688 goto set_str_and_exp;
1689 }
1690
Denys Vlasenko295fef82009-06-03 12:47:26 +02001691 /* Not found - create new variable struct */
1692 cur = xzalloc(sizeof(*cur));
1693#if ENABLE_HUSH_LOCAL
1694 cur->func_nest_level = local_lvl;
1695#endif
1696 cur->next = *var_pp;
1697 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001698
1699 set_str_and_exp:
1700 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001701#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001702 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001703#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001704 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001705 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001706 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001707 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1708 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001709 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001710 if (flg_export == -1) {
1711 cur->flg_export = 0;
1712 /* unsetenv was already done */
1713 } else {
1714 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1715 return putenv(cur->varstr);
1716 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001717 }
1718 return 0;
1719}
1720
Denys Vlasenko6db47842009-09-05 20:15:17 +02001721/* Used at startup and after each cd */
1722static void set_pwd_var(int exp)
1723{
1724 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1725 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1726}
1727
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001728static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001729{
1730 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001731 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001732
1733 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001734 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001735 var_pp = &G.top_var;
1736 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001737 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1738 if (cur->flg_read_only) {
1739 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001740 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001741 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001742 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001743 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1744 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001745 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1746 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001747 if (!cur->max_len)
1748 free(cur->varstr);
1749 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001750 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001751 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001752 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001753 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001754 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001755}
1756
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001757static int unset_local_var(const char *name)
1758{
1759 return unset_local_var_len(name, strlen(name));
1760}
1761
1762static void unset_vars(char **strings)
1763{
1764 char **v;
1765
1766 if (!strings)
1767 return;
1768 v = strings;
1769 while (*v) {
1770 const char *eq = strchrnul(*v, '=');
1771 unset_local_var_len(*v, (int)(eq - *v));
1772 v++;
1773 }
1774 free(strings);
1775}
1776
Denys Vlasenko03dad222010-01-12 23:29:57 +01001777static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001778{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001779 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001780 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001781}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001782
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001783
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001784/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001785 * Helpers for "var1=val1 var2=val2 cmd" feature
1786 */
1787static void add_vars(struct variable *var)
1788{
1789 struct variable *next;
1790
1791 while (var) {
1792 next = var->next;
1793 var->next = G.top_var;
1794 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001795 if (var->flg_export) {
1796 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001797 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001798 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001799 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001800 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001801 var = next;
1802 }
1803}
1804
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001805static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001806{
1807 char **s;
1808 struct variable *old = NULL;
1809
1810 if (!strings)
1811 return old;
1812 s = strings;
1813 while (*s) {
1814 struct variable *var_p;
1815 struct variable **var_pp;
1816 char *eq;
1817
1818 eq = strchr(*s, '=');
1819 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001820 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001821 if (var_pp) {
1822 /* Remove variable from global linked list */
1823 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001824 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001825 *var_pp = var_p->next;
1826 /* Add it to returned list */
1827 var_p->next = old;
1828 old = var_p;
1829 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001830 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001831 }
1832 s++;
1833 }
1834 return old;
1835}
1836
1837
1838/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001839 * in_str support
1840 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001841static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001842{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001843 int ch = *i->p;
1844 if (ch != '\0') {
1845 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001846 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001847 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001848 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001849}
1850
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001851static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001852{
1853 return *i->p;
1854}
1855
1856#if ENABLE_HUSH_INTERACTIVE
1857
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001858static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001859{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001860 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001861 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001862 if (G.PS1 == NULL)
1863 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001864 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001865 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001866 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001867 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001868 if (G.PS2 == NULL)
1869 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001870}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001871
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001872static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001873{
1874 const char *prompt_str;
1875 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001876 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1877 /* Set up the prompt */
1878 if (promptmode == 0) { /* PS1 */
1879 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001880 /* bash uses $PWD value, even if it is set by user.
1881 * It uses current dir only if PWD is unset.
1882 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001883 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001884 prompt_str = G.PS1;
1885 } else
1886 prompt_str = G.PS2;
1887 } else
1888 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001889 debug_printf("result '%s'\n", prompt_str);
1890 return prompt_str;
1891}
1892
1893static void get_user_input(struct in_str *i)
1894{
1895 int r;
1896 const char *prompt_str;
1897
1898 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001899# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001900 /* Enable command line editing only while a command line
1901 * is actually being read */
1902 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01001903 /* Unicode support should be activated even if LANG is set
1904 * _during_ shell execution, not only if it was set when
1905 * shell was started. Therefore, re-check LANG every time:
1906 */
1907 reinit_unicode(get_local_var_value("LANG"));
1908
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001909 G.flag_SIGINT = 0;
1910 /* buglet: SIGINT will not make new prompt to appear _at once_,
1911 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01001912 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 +00001913 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001914 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001915 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001916 i->eof_flag = (r < 0);
1917 if (i->eof_flag) { /* EOF/error detected */
1918 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1919 G.user_input_buf[1] = '\0';
1920 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001921# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001922 do {
1923 G.flag_SIGINT = 0;
1924 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001925 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001926 G.user_input_buf[0] = r = fgetc(i->file);
1927 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001928//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001929 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001930 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001931# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001932 i->p = G.user_input_buf;
1933}
1934
1935#endif /* INTERACTIVE */
1936
1937/* This is the magic location that prints prompts
1938 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001939static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001940{
1941 int ch;
1942
1943 /* If there is data waiting, eat it up */
1944 if (i->p && *i->p) {
1945#if ENABLE_HUSH_INTERACTIVE
1946 take_cached:
1947#endif
1948 ch = *i->p++;
1949 if (i->eof_flag && !*i->p)
1950 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001951 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001952 } else {
1953 /* need to double check i->file because we might be doing something
1954 * more complicated by now, like sourcing or substituting. */
1955#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01001956 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001957 do {
1958 get_user_input(i);
1959 } while (!*i->p); /* need non-empty line */
1960 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001961 goto take_cached;
1962 }
1963#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001964 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001965 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001966 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001967 return ch;
1968}
1969
Denis Vlasenko913a2012009-04-05 22:17:04 +00001970/* All callers guarantee this routine will never
1971 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001972 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001973static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001974{
1975 int ch;
1976 if (i->p && *i->p) {
1977 if (i->eof_flag && !i->p[1])
1978 return EOF;
1979 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001980 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001981 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001982 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001983 i->eof_flag = (ch == EOF);
1984 i->peek_buf[0] = ch;
1985 i->peek_buf[1] = '\0';
1986 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001987 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001988 return ch;
1989}
1990
1991static void setup_file_in_str(struct in_str *i, FILE *f)
1992{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01001993 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001994 i->peek = file_peek;
1995 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01001996 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001997 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01001998 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001999}
2000
2001static void setup_string_in_str(struct in_str *i, const char *s)
2002{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002003 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002004 i->peek = static_peek;
2005 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002006 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002007 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002008 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002009}
2010
2011
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002012/*
2013 * o_string support
2014 */
2015#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002016
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002017static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002018{
2019 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002020 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002021 if (o->data)
2022 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002023}
2024
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002025static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002026{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002027 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002028 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002029}
2030
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002031static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2032{
2033 free(o->data);
2034}
2035
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002036static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002037{
2038 if (o->length + len > o->maxlen) {
2039 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2040 o->data = xrealloc(o->data, 1 + o->maxlen);
2041 }
2042}
2043
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002044static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002045{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002046 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2047 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002048 o->data[o->length] = ch;
2049 o->length++;
2050 o->data[o->length] = '\0';
2051}
2052
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002053static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002054{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002055 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002056 memcpy(&o->data[o->length], str, len);
2057 o->length += len;
2058 o->data[o->length] = '\0';
2059}
2060
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002061static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002062{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002063 o_addblock(o, str, strlen(str));
2064}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002065
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002066#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002067static void nommu_addchr(o_string *o, int ch)
2068{
2069 if (o)
2070 o_addchr(o, ch);
2071}
2072#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002073# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002074#endif
2075
2076static void o_addstr_with_NUL(o_string *o, const char *str)
2077{
2078 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002079}
2080
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002081/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002082 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002083 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2084 * Apparently, on unquoted $v bash still does globbing
2085 * ("v='*.txt'; echo $v" prints all .txt files),
2086 * but NOT brace expansion! Thus, there should be TWO independent
2087 * quoting mechanisms on $v expansion side: one protects
2088 * $v from brace expansion, and other additionally protects "$v" against globbing.
2089 * We have only second one.
2090 */
2091
Denys Vlasenko9e800222010-10-03 14:28:04 +02002092#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002093# define MAYBE_BRACES "{}"
2094#else
2095# define MAYBE_BRACES ""
2096#endif
2097
Eric Andersen25f27032001-04-26 23:22:31 +00002098/* My analysis of quoting semantics tells me that state information
2099 * is associated with a destination, not a source.
2100 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002101static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002102{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002103 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002104 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002105 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002106 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002107 o_grow_by(o, sz);
2108 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002109 o->data[o->length] = '\\';
2110 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002111 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002112 o->data[o->length] = ch;
2113 o->length++;
2114 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002115}
2116
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002117static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002118{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002119 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002120 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2121 && strchr("*?[\\" MAYBE_BRACES, ch)
2122 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002123 sz++;
2124 o->data[o->length] = '\\';
2125 o->length++;
2126 }
2127 o_grow_by(o, sz);
2128 o->data[o->length] = ch;
2129 o->length++;
2130 o->data[o->length] = '\0';
2131}
2132
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002133static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002134{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002135 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002136 char ch;
2137 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002138 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002139 if (ordinary_cnt > len) /* paranoia */
2140 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002141 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002142 if (ordinary_cnt == len)
2143 return;
2144 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002145 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002146
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002147 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002148 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002149 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002150 sz++;
2151 o->data[o->length] = '\\';
2152 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002153 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002154 o_grow_by(o, sz);
2155 o->data[o->length] = ch;
2156 o->length++;
2157 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002158 }
2159}
2160
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002161static void o_addQblock(o_string *o, const char *str, int len)
2162{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002163 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002164 o_addblock(o, str, len);
2165 return;
2166 }
2167 o_addqblock(o, str, len);
2168}
2169
Denys Vlasenko38292b62010-09-05 14:49:40 +02002170static void o_addQstr(o_string *o, const char *str)
2171{
2172 o_addQblock(o, str, strlen(str));
2173}
2174
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002175/* A special kind of o_string for $VAR and `cmd` expansion.
2176 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002177 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002178 * list[i] contains an INDEX (int!) into this string data.
2179 * It means that if list[] needs to grow, data needs to be moved higher up
2180 * but list[i]'s need not be modified.
2181 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002182 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002183 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2184 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002185#if DEBUG_EXPAND || DEBUG_GLOB
2186static void debug_print_list(const char *prefix, o_string *o, int n)
2187{
2188 char **list = (char**)o->data;
2189 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2190 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002191
2192 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002193 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 +02002194 prefix, list, n, string_start, o->length, o->maxlen,
2195 !!(o->o_expflags & EXP_FLAG_GLOB),
2196 o->has_quoted_part,
2197 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002198 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002199 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002200 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2201 o->data + (int)(uintptr_t)list[i] + string_start,
2202 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002203 i++;
2204 }
2205 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002206 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002207 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002208 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002209 }
2210}
2211#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002212# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002213#endif
2214
2215/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2216 * in list[n] so that it points past last stored byte so far.
2217 * It returns n+1. */
2218static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002219{
2220 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002221 int string_start;
2222 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002223
2224 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002225 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2226 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002227 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002228 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002229 /* list[n] points to string_start, make space for 16 more pointers */
2230 o->maxlen += 0x10 * sizeof(list[0]);
2231 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002232 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002233 memmove(list + n + 0x10, list + n, string_len);
2234 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002235 } else {
2236 debug_printf_list("list[%d]=%d string_start=%d\n",
2237 n, string_len, string_start);
2238 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002239 } else {
2240 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002241 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2242 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002243 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2244 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002245 o->has_empty_slot = 0;
2246 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002247 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002248 return n + 1;
2249}
2250
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002251/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002252static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002253{
2254 char **list = (char**)o->data;
2255 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2256
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002257 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002258}
2259
Denys Vlasenko9e800222010-10-03 14:28:04 +02002260#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002261/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2262 * first, it processes even {a} (no commas), second,
2263 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002264 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002265 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002266
2267/* Helper */
2268static int glob_needed(const char *s)
2269{
2270 while (*s) {
2271 if (*s == '\\') {
2272 if (!s[1])
2273 return 0;
2274 s += 2;
2275 continue;
2276 }
2277 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2278 return 1;
2279 s++;
2280 }
2281 return 0;
2282}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002283/* Return pointer to next closing brace or to comma */
2284static const char *next_brace_sub(const char *cp)
2285{
2286 unsigned depth = 0;
2287 cp++;
2288 while (*cp != '\0') {
2289 if (*cp == '\\') {
2290 if (*++cp == '\0')
2291 break;
2292 cp++;
2293 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002294 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002295 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002296 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002297 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002298 depth++;
2299 }
2300
2301 return *cp != '\0' ? cp : NULL;
2302}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002303/* Recursive brace globber. Note: may garble pattern[]. */
2304static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002305{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002306 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002307 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002308 const char *next;
2309 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002310 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002311 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002312
2313 debug_printf_glob("glob_brace('%s')\n", pattern);
2314
2315 begin = pattern;
2316 while (1) {
2317 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002318 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002319 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002320 /* Find the first sub-pattern and at the same time
2321 * find the rest after the closing brace */
2322 next = next_brace_sub(begin);
2323 if (next == NULL) {
2324 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002325 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002326 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002327 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002328 /* "{abc}" with no commas - illegal
2329 * brace expr, disregard and skip it */
2330 begin = next + 1;
2331 continue;
2332 }
2333 break;
2334 }
2335 if (*begin == '\\' && begin[1] != '\0')
2336 begin++;
2337 begin++;
2338 }
2339 debug_printf_glob("begin:%s\n", begin);
2340 debug_printf_glob("next:%s\n", next);
2341
2342 /* Now find the end of the whole brace expression */
2343 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002344 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002345 rest = next_brace_sub(rest);
2346 if (rest == NULL) {
2347 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002348 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002349 }
2350 debug_printf_glob("rest:%s\n", rest);
2351 }
2352 rest_len = strlen(++rest) + 1;
2353
2354 /* We are sure the brace expression is well-formed */
2355
2356 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002357 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002358
2359 /* We have a brace expression. BEGIN points to the opening {,
2360 * NEXT points past the terminator of the first element, and REST
2361 * points past the final }. We will accumulate result names from
2362 * recursive runs for each brace alternative in the buffer using
2363 * GLOB_APPEND. */
2364
2365 p = begin + 1;
2366 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002367 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002368 memcpy(
2369 mempcpy(
2370 mempcpy(new_pattern_buf,
2371 /* We know the prefix for all sub-patterns */
2372 pattern, begin - pattern),
2373 p, next - p),
2374 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002375
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002376 /* Note: glob_brace() may garble new_pattern_buf[].
2377 * That's why we re-copy prefix every time (1st memcpy above).
2378 */
2379 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002380 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002381 /* We saw the last entry */
2382 break;
2383 }
2384 p = next + 1;
2385 next = next_brace_sub(next);
2386 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002387 free(new_pattern_buf);
2388 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002389
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002390 simple_glob:
2391 {
2392 int gr;
2393 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002394
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002395 memset(&globdata, 0, sizeof(globdata));
2396 gr = glob(pattern, 0, NULL, &globdata);
2397 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2398 if (gr != 0) {
2399 if (gr == GLOB_NOMATCH) {
2400 globfree(&globdata);
2401 /* NB: garbles parameter */
2402 unbackslash(pattern);
2403 o_addstr_with_NUL(o, pattern);
2404 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2405 return o_save_ptr_helper(o, n);
2406 }
2407 if (gr == GLOB_NOSPACE)
2408 bb_error_msg_and_die(bb_msg_memory_exhausted);
2409 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2410 * but we didn't specify it. Paranoia again. */
2411 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2412 }
2413 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2414 char **argv = globdata.gl_pathv;
2415 while (1) {
2416 o_addstr_with_NUL(o, *argv);
2417 n = o_save_ptr_helper(o, n);
2418 argv++;
2419 if (!*argv)
2420 break;
2421 }
2422 }
2423 globfree(&globdata);
2424 }
2425 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002426}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002427/* Performs globbing on last list[],
2428 * saving each result as a new list[].
2429 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002430static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002431{
2432 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002433
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002434 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002435 if (!o->data)
2436 return o_save_ptr_helper(o, n);
2437 pattern = o->data + o_get_last_ptr(o, n);
2438 debug_printf_glob("glob pattern '%s'\n", pattern);
2439 if (!glob_needed(pattern)) {
2440 /* unbackslash last string in o in place, fix length */
2441 o->length = unbackslash(pattern) - o->data;
2442 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2443 return o_save_ptr_helper(o, n);
2444 }
2445
2446 copy = xstrdup(pattern);
2447 /* "forget" pattern in o */
2448 o->length = pattern - o->data;
2449 n = glob_brace(copy, o, n);
2450 free(copy);
2451 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002452 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002453 return n;
2454}
2455
Denys Vlasenko238081f2010-10-03 14:26:26 +02002456#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002457
2458/* Helper */
2459static int glob_needed(const char *s)
2460{
2461 while (*s) {
2462 if (*s == '\\') {
2463 if (!s[1])
2464 return 0;
2465 s += 2;
2466 continue;
2467 }
2468 if (*s == '*' || *s == '[' || *s == '?')
2469 return 1;
2470 s++;
2471 }
2472 return 0;
2473}
2474/* Performs globbing on last list[],
2475 * saving each result as a new list[].
2476 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002477static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002478{
2479 glob_t globdata;
2480 int gr;
2481 char *pattern;
2482
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002483 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002484 if (!o->data)
2485 return o_save_ptr_helper(o, n);
2486 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002487 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002488 if (!glob_needed(pattern)) {
2489 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002490 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002491 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002492 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002493 return o_save_ptr_helper(o, n);
2494 }
2495
2496 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002497 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2498 * If we glob "*.\*" and don't find anything, we need
2499 * to fall back to using literal "*.*", but GLOB_NOCHECK
2500 * will return "*.\*"!
2501 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002502 gr = glob(pattern, 0, NULL, &globdata);
2503 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002504 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002505 if (gr == GLOB_NOMATCH) {
2506 globfree(&globdata);
2507 goto literal;
2508 }
2509 if (gr == GLOB_NOSPACE)
2510 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002511 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2512 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002513 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002514 }
2515 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2516 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002517 /* "forget" pattern in o */
2518 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002519 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002520 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002521 n = o_save_ptr_helper(o, n);
2522 argv++;
2523 if (!*argv)
2524 break;
2525 }
2526 }
2527 globfree(&globdata);
2528 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002529 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002530 return n;
2531}
2532
Denys Vlasenko238081f2010-10-03 14:26:26 +02002533#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002534
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002535/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002536 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002537static int o_save_ptr(o_string *o, int n)
2538{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002539 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002540 /* If o->has_empty_slot, list[n] was already globbed
2541 * (if it was requested back then when it was filled)
2542 * so don't do that again! */
2543 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002544 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002545 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002546 return o_save_ptr_helper(o, n);
2547}
2548
2549/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002550static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002551{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002552 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002553 int string_start;
2554
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002555 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2556 if (DEBUG_EXPAND)
2557 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002558 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002559 list = (char**)o->data;
2560 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2561 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002562 while (n) {
2563 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002564 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002565 }
2566 return list;
2567}
2568
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002569static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002570
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002571/* Returns pi->next - next pipe in the list */
2572static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002573{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002574 struct pipe *next;
2575 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002576
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002577 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002578 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002579 struct command *command;
2580 struct redir_struct *r, *rnext;
2581
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002582 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002583 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002584 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002585 if (DEBUG_CLEAN) {
2586 int a;
2587 char **p;
2588 for (a = 0, p = command->argv; *p; a++, p++) {
2589 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2590 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002591 }
2592 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002593 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002594 }
2595 /* not "else if": on syntax error, we may have both! */
2596 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002597 debug_printf_clean(" begin group (cmd_type:%d)\n",
2598 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002599 free_pipe_list(command->group);
2600 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002601 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002602 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002603 /* else is crucial here.
2604 * If group != NULL, child_func is meaningless */
2605#if ENABLE_HUSH_FUNCTIONS
2606 else if (command->child_func) {
2607 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2608 command->child_func->parent_cmd = NULL;
2609 }
2610#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002611#if !BB_MMU
2612 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002613 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002614#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002615 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002616 debug_printf_clean(" redirect %d%s",
2617 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002618 /* guard against the case >$FOO, where foo is unset or blank */
2619 if (r->rd_filename) {
2620 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2621 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002622 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002623 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002624 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002625 rnext = r->next;
2626 free(r);
2627 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002628 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002629 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002630 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002631 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002632#if ENABLE_HUSH_JOB
2633 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002634 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002635#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002636
2637 next = pi->next;
2638 free(pi);
2639 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002640}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002641
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002642static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002643{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002644 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002645#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002646 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002647#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002648 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002649 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002650 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002651}
2652
2653
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002654/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002655
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002656#ifndef debug_print_tree
2657static void debug_print_tree(struct pipe *pi, int lvl)
2658{
2659 static const char *const PIPE[] = {
2660 [PIPE_SEQ] = "SEQ",
2661 [PIPE_AND] = "AND",
2662 [PIPE_OR ] = "OR" ,
2663 [PIPE_BG ] = "BG" ,
2664 };
2665 static const char *RES[] = {
2666 [RES_NONE ] = "NONE" ,
2667# if ENABLE_HUSH_IF
2668 [RES_IF ] = "IF" ,
2669 [RES_THEN ] = "THEN" ,
2670 [RES_ELIF ] = "ELIF" ,
2671 [RES_ELSE ] = "ELSE" ,
2672 [RES_FI ] = "FI" ,
2673# endif
2674# if ENABLE_HUSH_LOOPS
2675 [RES_FOR ] = "FOR" ,
2676 [RES_WHILE] = "WHILE",
2677 [RES_UNTIL] = "UNTIL",
2678 [RES_DO ] = "DO" ,
2679 [RES_DONE ] = "DONE" ,
2680# endif
2681# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2682 [RES_IN ] = "IN" ,
2683# endif
2684# if ENABLE_HUSH_CASE
2685 [RES_CASE ] = "CASE" ,
2686 [RES_CASE_IN ] = "CASE_IN" ,
2687 [RES_MATCH] = "MATCH",
2688 [RES_CASE_BODY] = "CASE_BODY",
2689 [RES_ESAC ] = "ESAC" ,
2690# endif
2691 [RES_XXXX ] = "XXXX" ,
2692 [RES_SNTX ] = "SNTX" ,
2693 };
2694 static const char *const CMDTYPE[] = {
2695 "{}",
2696 "()",
2697 "[noglob]",
2698# if ENABLE_HUSH_FUNCTIONS
2699 "func()",
2700# endif
2701 };
2702
2703 int pin, prn;
2704
2705 pin = 0;
2706 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002707 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002708 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2709 prn = 0;
2710 while (prn < pi->num_cmds) {
2711 struct command *command = &pi->cmds[prn];
2712 char **argv = command->argv;
2713
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002714 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002715 lvl*2, "", prn,
2716 command->assignment_cnt);
2717 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002718 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002719 CMDTYPE[command->cmd_type],
2720 argv
2721# if !BB_MMU
2722 , " group_as_string:", command->group_as_string
2723# else
2724 , "", ""
2725# endif
2726 );
2727 debug_print_tree(command->group, lvl+1);
2728 prn++;
2729 continue;
2730 }
2731 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002732 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002733 argv++;
2734 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002735 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002736 prn++;
2737 }
2738 pi = pi->next;
2739 pin++;
2740 }
2741}
2742#endif /* debug_print_tree */
2743
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002744static struct pipe *new_pipe(void)
2745{
Eric Andersen25f27032001-04-26 23:22:31 +00002746 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002747 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002748 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002749 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002750 return pi;
2751}
2752
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002753/* Command (member of a pipe) is complete, or we start a new pipe
2754 * if ctx->command is NULL.
2755 * No errors possible here.
2756 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002757static int done_command(struct parse_context *ctx)
2758{
2759 /* The command is really already in the pipe structure, so
2760 * advance the pipe counter and make a new, null command. */
2761 struct pipe *pi = ctx->pipe;
2762 struct command *command = ctx->command;
2763
2764 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002765 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002766 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002767 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002768 }
2769 pi->num_cmds++;
2770 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002771 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002772 } else {
2773 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2774 }
2775
2776 /* Only real trickiness here is that the uncommitted
2777 * command structure is not counted in pi->num_cmds. */
2778 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002779 ctx->command = command = &pi->cmds[pi->num_cmds];
2780 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002781 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002782 return pi->num_cmds; /* used only for 0/nonzero check */
2783}
2784
2785static void done_pipe(struct parse_context *ctx, pipe_style type)
2786{
2787 int not_null;
2788
2789 debug_printf_parse("done_pipe entered, followup %d\n", type);
2790 /* Close previous command */
2791 not_null = done_command(ctx);
2792 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002793#if HAS_KEYWORDS
2794 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2795 ctx->ctx_inverted = 0;
2796 ctx->pipe->res_word = ctx->ctx_res_w;
2797#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002798
2799 /* Without this check, even just <enter> on command line generates
2800 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002801 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002802 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002803#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002804 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002805#endif
2806#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002807 || ctx->ctx_res_w == RES_DONE
2808 || ctx->ctx_res_w == RES_FOR
2809 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002810#endif
2811#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002812 || ctx->ctx_res_w == RES_ESAC
2813#endif
2814 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002815 struct pipe *new_p;
2816 debug_printf_parse("done_pipe: adding new pipe: "
2817 "not_null:%d ctx->ctx_res_w:%d\n",
2818 not_null, ctx->ctx_res_w);
2819 new_p = new_pipe();
2820 ctx->pipe->next = new_p;
2821 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002822 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002823 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002824 * This is used to control execution.
2825 * RES_FOR and RES_IN are NOT sticky (needed to support
2826 * cases where variable or value happens to match a keyword):
2827 */
2828#if ENABLE_HUSH_LOOPS
2829 if (ctx->ctx_res_w == RES_FOR
2830 || ctx->ctx_res_w == RES_IN)
2831 ctx->ctx_res_w = RES_NONE;
2832#endif
2833#if ENABLE_HUSH_CASE
2834 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002835 ctx->ctx_res_w = RES_CASE_BODY;
2836 if (ctx->ctx_res_w == RES_CASE)
2837 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002838#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002839 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002840 /* Create the memory for command, roughly:
2841 * ctx->pipe->cmds = new struct command;
2842 * ctx->command = &ctx->pipe->cmds[0];
2843 */
2844 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002845 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002846 }
2847 debug_printf_parse("done_pipe return\n");
2848}
2849
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002850static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002851{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002852 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002853 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002854 /* Create the memory for command, roughly:
2855 * ctx->pipe->cmds = new struct command;
2856 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002857 */
2858 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002859}
2860
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002861/* If a reserved word is found and processed, parse context is modified
2862 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002863 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002864#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002865struct reserved_combo {
2866 char literal[6];
2867 unsigned char res;
2868 unsigned char assignment_flag;
2869 int flag;
2870};
2871enum {
2872 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002873# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002874 FLAG_IF = (1 << RES_IF ),
2875 FLAG_THEN = (1 << RES_THEN ),
2876 FLAG_ELIF = (1 << RES_ELIF ),
2877 FLAG_ELSE = (1 << RES_ELSE ),
2878 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002879# endif
2880# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002881 FLAG_FOR = (1 << RES_FOR ),
2882 FLAG_WHILE = (1 << RES_WHILE),
2883 FLAG_UNTIL = (1 << RES_UNTIL),
2884 FLAG_DO = (1 << RES_DO ),
2885 FLAG_DONE = (1 << RES_DONE ),
2886 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002887# endif
2888# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002889 FLAG_MATCH = (1 << RES_MATCH),
2890 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002891# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002892 FLAG_START = (1 << RES_XXXX ),
2893};
2894
2895static const struct reserved_combo* match_reserved_word(o_string *word)
2896{
Eric Andersen25f27032001-04-26 23:22:31 +00002897 /* Mostly a list of accepted follow-up reserved words.
2898 * FLAG_END means we are done with the sequence, and are ready
2899 * to turn the compound list into a command.
2900 * FLAG_START means the word must start a new compound list.
2901 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002902 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002903# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002904 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2905 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2906 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2907 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2908 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2909 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002910# endif
2911# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002912 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2913 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2914 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2915 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2916 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2917 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002918# endif
2919# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002920 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2921 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002922# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002923 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002924 const struct reserved_combo *r;
2925
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02002926 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002927 if (strcmp(word->data, r->literal) == 0)
2928 return r;
2929 }
2930 return NULL;
2931}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002932/* Return 0: not a keyword, 1: keyword
2933 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002934static int reserved_word(o_string *word, struct parse_context *ctx)
2935{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002936# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002937 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002938 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002939 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002940# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002941 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002942
Denys Vlasenko38292b62010-09-05 14:49:40 +02002943 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002944 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002945 r = match_reserved_word(word);
2946 if (!r)
2947 return 0;
2948
2949 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002950# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002951 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2952 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002953 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002954 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002955# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002956 if (r->flag == 0) { /* '!' */
2957 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002958 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002959 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002960 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002961 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002962 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002963 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002964 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002965 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002966
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002967 old = xmalloc(sizeof(*old));
2968 debug_printf_parse("push stack %p\n", old);
2969 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002970 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002971 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002972 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002973 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002974 ctx->ctx_res_w = RES_SNTX;
2975 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002976 } else {
2977 /* "{...} fi" is ok. "{...} if" is not
2978 * Example:
2979 * if { echo foo; } then { echo bar; } fi */
2980 if (ctx->command->group)
2981 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002982 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002983
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002984 ctx->ctx_res_w = r->res;
2985 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002986 word->o_assignment = r->assignment_flag;
2987
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002988 if (ctx->old_flag & FLAG_END) {
2989 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002990
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002991 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002992 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002993 old = ctx->stack;
2994 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002995 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002996# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002997 o_addstr(&old->as_string, ctx->as_string.data);
2998 o_free_unsafe(&ctx->as_string);
2999 old->command->group_as_string = xstrdup(old->as_string.data);
3000 debug_printf_parse("pop, remembering as:'%s'\n",
3001 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003002# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003003 *ctx = *old; /* physical copy */
3004 free(old);
3005 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003006 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003007}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003008#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003009
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003010/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003011 * Normal return is 0. Syntax errors return 1.
3012 * Note: on return, word is reset, but not o_free'd!
3013 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003014static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003015{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003016 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003017
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003018 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003019 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003020 debug_printf_parse("done_word return 0: true null, ignored\n");
3021 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003022 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003023
Eric Andersen25f27032001-04-26 23:22:31 +00003024 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003025 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3026 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003027 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3028 * "2.7 Redirection
3029 * ...the word that follows the redirection operator
3030 * shall be subjected to tilde expansion, parameter expansion,
3031 * command substitution, arithmetic expansion, and quote
3032 * removal. Pathname expansion shall not be performed
3033 * on the word by a non-interactive shell; an interactive
3034 * shell may perform it, but shall do so only when
3035 * the expansion would result in one word."
3036 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003037 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003038 /* Cater for >\file case:
3039 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3040 * Same with heredocs:
3041 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3042 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003043 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3044 unbackslash(ctx->pending_redirect->rd_filename);
3045 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003046 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003047 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3048 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003049 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003050 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003051 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003052 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003053 /* If this word wasn't an assignment, next ones definitely
3054 * can't be assignments. Even if they look like ones. */
3055 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3056 && word->o_assignment != WORD_IS_KEYWORD
3057 ) {
3058 word->o_assignment = NOT_ASSIGNMENT;
3059 } else {
3060 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3061 command->assignment_cnt++;
3062 word->o_assignment = MAYBE_ASSIGNMENT;
3063 }
3064
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003065#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003066# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003067 if (ctx->ctx_dsemicolon
3068 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3069 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003070 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003071 /* ctx->ctx_res_w = RES_MATCH; */
3072 ctx->ctx_dsemicolon = 0;
3073 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003074# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003075 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003076# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003077 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3078 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003079# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003080# if ENABLE_HUSH_CASE
3081 && ctx->ctx_res_w != RES_CASE
3082# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003083 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003084 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003085 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003086 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003087 debug_printf_parse("done_word return %d\n",
3088 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003089 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003090 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003091# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003092 if (strcmp(word->data, "[[") == 0) {
3093 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3094 }
3095 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003096# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003097 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003098#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003099 if (command->group) {
3100 /* "{ echo foo; } echo bar" - bad */
3101 syntax_error_at(word->data);
3102 debug_printf_parse("done_word return 1: syntax error, "
3103 "groups and arglists don't mix\n");
3104 return 1;
3105 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02003106 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003107 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3108 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003109 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003110 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003111 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003112 char *p = word->data;
3113 while (p[0] == SPECIAL_VAR_SYMBOL
3114 && (p[1] & 0x7f) == '@'
3115 && p[2] == SPECIAL_VAR_SYMBOL
3116 ) {
3117 p += 3;
3118 }
3119 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003120 /* saw no "$@", or not only "$@" but some
3121 * real text is there too */
3122 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003123 * e.g. "", $empty"" etc to not disappear */
3124 o_addchr(word, SPECIAL_VAR_SYMBOL);
3125 o_addchr(word, SPECIAL_VAR_SYMBOL);
3126 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003127 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003128 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003129 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003130 }
Eric Andersen25f27032001-04-26 23:22:31 +00003131
Denis Vlasenko06810332007-05-21 23:30:54 +00003132#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003133 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003134 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003135 || !is_well_formed_var_name(command->argv[0], '\0')
3136 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003137 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003138 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003139 return 1;
3140 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003141 /* Force FOR to have just one word (variable name) */
3142 /* NB: basically, this makes hush see "for v in ..."
3143 * syntax as if it is "for v; in ...". FOR and IN become
3144 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003145 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003146 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003147#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003148#if ENABLE_HUSH_CASE
3149 /* Force CASE to have just one word */
3150 if (ctx->ctx_res_w == RES_CASE) {
3151 done_pipe(ctx, PIPE_SEQ);
3152 }
3153#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003154
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003155 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003156
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003157 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003158 return 0;
3159}
3160
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003161
3162/* Peek ahead in the input to find out if we have a "&n" construct,
3163 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003164 * Return:
3165 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3166 * REDIRFD_SYNTAX_ERR if syntax error,
3167 * REDIRFD_TO_FILE if no & was seen,
3168 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003169 */
3170#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003171#define parse_redir_right_fd(as_string, input) \
3172 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003173#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003174static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003175{
3176 int ch, d, ok;
3177
3178 ch = i_peek(input);
3179 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003180 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003181
3182 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003183 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003184 ch = i_peek(input);
3185 if (ch == '-') {
3186 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003187 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003188 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003189 }
3190 d = 0;
3191 ok = 0;
3192 while (ch != EOF && isdigit(ch)) {
3193 d = d*10 + (ch-'0');
3194 ok = 1;
3195 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003196 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003197 ch = i_peek(input);
3198 }
3199 if (ok) return d;
3200
3201//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3202
3203 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003204 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003205}
3206
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003207/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003208 */
3209static int parse_redirect(struct parse_context *ctx,
3210 int fd,
3211 redir_type style,
3212 struct in_str *input)
3213{
3214 struct command *command = ctx->command;
3215 struct redir_struct *redir;
3216 struct redir_struct **redirp;
3217 int dup_num;
3218
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003219 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003220 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003221 /* Check for a '>&1' type redirect */
3222 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3223 if (dup_num == REDIRFD_SYNTAX_ERR)
3224 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003225 } else {
3226 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003227 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003228 if (dup_num) { /* <<-... */
3229 ch = i_getch(input);
3230 nommu_addchr(&ctx->as_string, ch);
3231 ch = i_peek(input);
3232 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003233 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003234
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003235 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003236 int ch = i_peek(input);
3237 if (ch == '|') {
3238 /* >|FILE redirect ("clobbering" >).
3239 * Since we do not support "set -o noclobber" yet,
3240 * >| and > are the same for now. Just eat |.
3241 */
3242 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003243 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003244 }
3245 }
3246
3247 /* Create a new redir_struct and append it to the linked list */
3248 redirp = &command->redirects;
3249 while ((redir = *redirp) != NULL) {
3250 redirp = &(redir->next);
3251 }
3252 *redirp = redir = xzalloc(sizeof(*redir));
3253 /* redir->next = NULL; */
3254 /* redir->rd_filename = NULL; */
3255 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003256 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003257
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003258 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3259 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003260
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003261 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003262 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003263 /* Erik had a check here that the file descriptor in question
3264 * is legit; I postpone that to "run time"
3265 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003266 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3267 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003268 } else {
3269 /* Set ctx->pending_redirect, so we know what to do at the
3270 * end of the next parsed word. */
3271 ctx->pending_redirect = redir;
3272 }
3273 return 0;
3274}
3275
Eric Andersen25f27032001-04-26 23:22:31 +00003276/* If a redirect is immediately preceded by a number, that number is
3277 * supposed to tell which file descriptor to redirect. This routine
3278 * looks for such preceding numbers. In an ideal world this routine
3279 * needs to handle all the following classes of redirects...
3280 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3281 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3282 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3283 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003284 *
3285 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3286 * "2.7 Redirection
3287 * ... If n is quoted, the number shall not be recognized as part of
3288 * the redirection expression. For example:
3289 * echo \2>a
3290 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003291 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003292 *
3293 * A -1 return means no valid number was found,
3294 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003295 */
3296static int redirect_opt_num(o_string *o)
3297{
3298 int num;
3299
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003300 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003301 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003302 num = bb_strtou(o->data, NULL, 10);
3303 if (errno || num < 0)
3304 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003305 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003306 return num;
3307}
3308
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003309#if BB_MMU
3310#define fetch_till_str(as_string, input, word, skip_tabs) \
3311 fetch_till_str(input, word, skip_tabs)
3312#endif
3313static char *fetch_till_str(o_string *as_string,
3314 struct in_str *input,
3315 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003316 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003317{
3318 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003319 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003320 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003321 int ch;
3322
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003323 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003324 while (1) {
3325 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003326 if (ch != EOF)
3327 nommu_addchr(as_string, ch);
3328 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003329 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3330 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003331 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3332 heredoc.data[past_EOL] = '\0';
3333 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3334 return heredoc.data;
3335 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003336 while (ch == '\n') {
3337 o_addchr(&heredoc, ch);
3338 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003339 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003340 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003341 do {
3342 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003343 if (ch != EOF)
3344 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003345 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003346 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003347 }
3348 if (ch == EOF) {
3349 o_free_unsafe(&heredoc);
3350 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003351 }
3352 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003353 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003354 if (prev == '\\' && ch == '\\')
3355 /* Correctly handle foo\\<eol> (not a line cont.) */
3356 prev = 0; /* not \ */
3357 else
3358 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003359 }
3360}
3361
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003362/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3363 * and load them all. There should be exactly heredoc_cnt of them.
3364 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003365static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3366{
3367 struct pipe *pi = ctx->list_head;
3368
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003369 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003370 int i;
3371 struct command *cmd = pi->cmds;
3372
3373 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3374 pi->num_cmds,
3375 cmd->argv ? cmd->argv[0] : "NONE");
3376 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003377 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003378
3379 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3380 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003381 while (redir) {
3382 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003383 char *p;
3384
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003385 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003386 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003387 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003388 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003389 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003390 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003391 return 1;
3392 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003393 free(redir->rd_filename);
3394 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003395 heredoc_cnt--;
3396 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003397 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003398 }
3399 cmd++;
3400 }
3401 pi = pi->next;
3402 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003403#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003404 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003405 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003406 bb_error_msg_and_die("heredoc BUG 2");
3407#endif
3408 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003409}
3410
3411
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003412static int run_list(struct pipe *pi);
3413#if BB_MMU
3414#define parse_stream(pstring, input, end_trigger) \
3415 parse_stream(input, end_trigger)
3416#endif
3417static struct pipe *parse_stream(char **pstring,
3418 struct in_str *input,
3419 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003420
Eric Andersen25f27032001-04-26 23:22:31 +00003421
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003422#if !ENABLE_HUSH_FUNCTIONS
3423#define parse_group(dest, ctx, input, ch) \
3424 parse_group(ctx, input, ch)
3425#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003426static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003427 struct in_str *input, int ch)
3428{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003429 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003430 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003431 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003432 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003433 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003434 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003435
3436 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003437#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003438 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003439 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003440 if (done_word(dest, ctx))
3441 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003442 if (!command->argv)
3443 goto skip; /* (... */
3444 if (command->argv[1]) { /* word word ... (... */
3445 syntax_error_unexpected_ch('(');
3446 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003447 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003448 /* it is "word(..." or "word (..." */
3449 do
3450 ch = i_getch(input);
3451 while (ch == ' ' || ch == '\t');
3452 if (ch != ')') {
3453 syntax_error_unexpected_ch(ch);
3454 return 1;
3455 }
3456 nommu_addchr(&ctx->as_string, ch);
3457 do
3458 ch = i_getch(input);
3459 while (ch == ' ' || ch == '\t' || ch == '\n');
3460 if (ch != '{') {
3461 syntax_error_unexpected_ch(ch);
3462 return 1;
3463 }
3464 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003465 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003466 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003467 }
3468#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003469
3470#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003471 if (command->argv /* word [word]{... */
3472 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003473 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003474 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003475 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003476 debug_printf_parse("parse_group return 1: "
3477 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003478 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003479 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003480#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003481
3482#if ENABLE_HUSH_FUNCTIONS
3483 skip:
3484#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003485 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003486 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003487 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003488 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003489 } else {
3490 /* bash does not allow "{echo...", requires whitespace */
3491 ch = i_getch(input);
3492 if (ch != ' ' && ch != '\t' && ch != '\n') {
3493 syntax_error_unexpected_ch(ch);
3494 return 1;
3495 }
3496 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003497 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003498
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003499 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003500#if BB_MMU
3501# define as_string NULL
3502#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003503 char *as_string = NULL;
3504#endif
3505 pipe_list = parse_stream(&as_string, input, endch);
3506#if !BB_MMU
3507 if (as_string)
3508 o_addstr(&ctx->as_string, as_string);
3509#endif
3510 /* empty ()/{} or parse error? */
3511 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003512 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003513 if (!BB_MMU)
3514 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003515 debug_printf_parse("parse_group return 1: "
3516 "parse_stream returned %p\n", pipe_list);
3517 return 1;
3518 }
3519 command->group = pipe_list;
3520#if !BB_MMU
3521 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3522 command->group_as_string = as_string;
3523 debug_printf_parse("end of group, remembering as:'%s'\n",
3524 command->group_as_string);
3525#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003526#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003527 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003528 debug_printf_parse("parse_group return 0\n");
3529 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003530 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003531}
3532
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003533#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003534/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003535static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003536/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003537static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003538{
3539 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003540 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003541 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003542 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003543 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003544 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003545 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003546 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003547 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003548 }
3549}
3550/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003551static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003552{
3553 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003554 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003555 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003556 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003557 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003558 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003559 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003560 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003561 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003562 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003563 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003564 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003565 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003566 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003567 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3568 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003569 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003570 continue;
3571 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003572 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003573 }
3574}
3575/* Process `cmd` - copy contents until "`" is seen. Complicated by
3576 * \` quoting.
3577 * "Within the backquoted style of command substitution, backslash
3578 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3579 * The search for the matching backquote shall be satisfied by the first
3580 * backquote found without a preceding backslash; during this search,
3581 * if a non-escaped backquote is encountered within a shell comment,
3582 * a here-document, an embedded command substitution of the $(command)
3583 * form, or a quoted string, undefined results occur. A single-quoted
3584 * or double-quoted string that begins, but does not end, within the
3585 * "`...`" sequence produces undefined results."
3586 * Example Output
3587 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3588 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003589static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003590{
3591 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003592 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003593 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003594 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003595 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003596 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3597 ch = i_getch(input);
3598 if (ch != '`'
3599 && ch != '$'
3600 && ch != '\\'
3601 && (!in_dquote || ch != '"')
3602 ) {
3603 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003604 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003605 }
3606 if (ch == EOF) {
3607 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003608 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003609 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003610 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003611 }
3612}
3613/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3614 * quoting and nested ()s.
3615 * "With the $(command) style of command substitution, all characters
3616 * following the open parenthesis to the matching closing parenthesis
3617 * constitute the command. Any valid shell script can be used for command,
3618 * except a script consisting solely of redirections which produces
3619 * unspecified results."
3620 * Example Output
3621 * echo $(echo '(TEST)' BEST) (TEST) BEST
3622 * echo $(echo 'TEST)' BEST) TEST) BEST
3623 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003624 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003625 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003626 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003627 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3628 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003629 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003630#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003631static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003632{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003633 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003634 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003635# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003636 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003637# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003638 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3639
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003640 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003641 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003642 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003643 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003644 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003645 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003646 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003647 if (!dbl)
3648 break;
3649 /* we look for closing )) of $((EXPR)) */
3650 if (i_peek(input) == end_ch) {
3651 i_getch(input); /* eat second ')' */
3652 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003653 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003654 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003655 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003656 if (ch == '(' || ch == '{') {
3657 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003658 if (!add_till_closing_bracket(dest, input, ch))
3659 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003660 o_addchr(dest, ch);
3661 continue;
3662 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003663 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003664 if (!add_till_single_quote(dest, input))
3665 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003666 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003667 continue;
3668 }
3669 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003670 if (!add_till_double_quote(dest, input))
3671 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003672 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003673 continue;
3674 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003675 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003676 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3677 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003678 o_addchr(dest, ch);
3679 continue;
3680 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003681 if (ch == '\\') {
3682 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003683 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003684 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003685 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003686 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003687 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003688 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003689 continue;
3690 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003691 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003692 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003693}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003694#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003695
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003696/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003697#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003698#define parse_dollar(as_string, dest, input, quote_mask) \
3699 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003700#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003701#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003702static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003703 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003704 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003705{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003706 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003707
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003708 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003709 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003710 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003711 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003712 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003713 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003714 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003715 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003716 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003717 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003718 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003719 if (!isalnum(ch) && ch != '_')
3720 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003721 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003722 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003723 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003724 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003725 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003726 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003727 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003728 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003729 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003730 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003731 o_addchr(dest, ch | quote_mask);
3732 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003733 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003734 case '$': /* pid */
3735 case '!': /* last bg pid */
3736 case '?': /* last exit code */
3737 case '#': /* number of args */
3738 case '*': /* args */
3739 case '@': /* args */
3740 goto make_one_char_var;
3741 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003742 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3743
Denys Vlasenko74369502010-05-21 19:52:01 +02003744 ch = i_getch(input); /* eat '{' */
3745 nommu_addchr(as_string, ch);
3746
3747 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003748 /* It should be ${?}, or ${#var},
3749 * or even ${?+subst} - operator acting on a special variable,
3750 * or the beginning of variable name.
3751 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003752 if (ch == EOF
3753 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3754 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003755 bad_dollar_syntax:
3756 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003757 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3758 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02003759 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003760 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003761 ch |= quote_mask;
3762
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003763 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003764 * However, this regresses some of our testsuite cases
3765 * which check invalid constructs like ${%}.
3766 * Oh well... let's check that the var name part is fine... */
3767
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003768 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003769 unsigned pos;
3770
Denys Vlasenko74369502010-05-21 19:52:01 +02003771 o_addchr(dest, ch);
3772 debug_printf_parse(": '%c'\n", ch);
3773
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003774 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003775 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003776 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003777 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003778
Denys Vlasenko74369502010-05-21 19:52:01 +02003779 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003780 unsigned end_ch;
3781 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003782 /* handle parameter expansions
3783 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3784 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003785 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003786 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003787
3788 /* Eat everything until closing '}' (or ':') */
3789 end_ch = '}';
3790 if (ENABLE_HUSH_BASH_COMPAT
3791 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003792 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003793 ) {
3794 /* It's ${var:N[:M]} thing */
3795 end_ch = '}' * 0x100 + ':';
3796 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003797 if (ENABLE_HUSH_BASH_COMPAT
3798 && ch == '/'
3799 ) {
3800 /* It's ${var/[/]pattern[/repl]} thing */
3801 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3802 i_getch(input);
3803 nommu_addchr(as_string, '/');
3804 ch = '\\';
3805 }
3806 end_ch = '}' * 0x100 + '/';
3807 }
3808 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003809 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003810 if (!BB_MMU)
3811 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003812#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003813 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003814 if (last_ch == 0) /* error? */
3815 return 0;
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;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003860 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
3861 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003862 if (as_string) {
3863 o_addstr(as_string, dest->data + pos);
3864 o_addchr(as_string, ')');
3865 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003866 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003867 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003868 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003869 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003870# endif
3871# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003872 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3873 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003874 if (!BB_MMU)
3875 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003876 if (!add_till_closing_bracket(dest, input, ')'))
3877 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003878 if (as_string) {
3879 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003880 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003881 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003882 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003883# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003884 break;
3885 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003886#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003887 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003888 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003889 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003890 ch = i_peek(input);
3891 if (isalnum(ch)) { /* it's $_name or $_123 */
3892 ch = '_';
3893 goto make_var;
3894 }
3895 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003896 /* TODO: $_ and $-: */
3897 /* $_ Shell or shell script name; or last argument of last command
3898 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3899 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003900 /* $- Option flags set by set builtin or shell options (-i etc) */
3901 default:
3902 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003903 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003904 debug_printf_parse("parse_dollar return 1 (ok)\n");
3905 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003906#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003907}
3908
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003909#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003910# if ENABLE_HUSH_BASH_COMPAT
3911#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3912 encode_string(dest, input, dquote_end, process_bkslash)
3913# else
3914/* only ${var/pattern/repl} (its pattern part) needs additional mode */
3915#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3916 encode_string(dest, input, dquote_end)
3917# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003918#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003919
3920#else /* !MMU */
3921
3922# if ENABLE_HUSH_BASH_COMPAT
3923/* all parameters are needed, no macro tricks */
3924# else
3925#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3926 encode_string(as_string, dest, input, dquote_end)
3927# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003928#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003929static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003930 o_string *dest,
3931 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02003932 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003933 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003934{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003935#if !ENABLE_HUSH_BASH_COMPAT
3936 const int process_bkslash = 1;
3937#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003938 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003939 int next;
3940
3941 again:
3942 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003943 if (ch != EOF)
3944 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003945 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003946 debug_printf_parse("encode_string return 1 (ok)\n");
3947 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003948 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003949 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003950 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003951 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003952 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003953 }
3954 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003955 if (ch != '\n') {
3956 next = i_peek(input);
3957 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003958 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003959 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003960 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003961 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003962 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003963 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003964 }
3965 /* bash:
3966 * "The backslash retains its special meaning [in "..."]
3967 * only when followed by one of the following characters:
3968 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003969 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003970 * NB: in (unquoted) heredoc, above does not apply to ",
3971 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003972 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003973 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003974 ch = i_getch(input); /* eat next */
3975 if (ch == '\n')
3976 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02003977 } /* else: ch remains == '\\', and we double it below: */
3978 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003979 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003980 goto again;
3981 }
3982 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003983 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
3984 debug_printf_parse("encode_string return 0: "
3985 "parse_dollar returned 0 (error)\n");
3986 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003987 }
3988 goto again;
3989 }
3990#if ENABLE_HUSH_TICK
3991 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003992 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003993 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3994 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003995 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
3996 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003997 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3998 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003999 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004000 }
4001#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004002 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004003 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004004#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004005}
4006
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004007/*
4008 * Scan input until EOF or end_trigger char.
4009 * Return a list of pipes to execute, or NULL on EOF
4010 * or if end_trigger character is met.
4011 * On syntax error, exit is shell is not interactive,
4012 * reset parsing machinery and start parsing anew,
4013 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004014 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004015static struct pipe *parse_stream(char **pstring,
4016 struct in_str *input,
4017 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004018{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004019 struct parse_context ctx;
4020 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004021 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004022
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004023 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004024 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004025 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004026 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004027 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004028 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004029
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004030 /* If very first arg is "" or '', dest.data may end up NULL.
4031 * Preventing this: */
4032 o_addchr(&dest, '\0');
4033 dest.length = 0;
4034
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004035 /* We used to separate words on $IFS here. This was wrong.
4036 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004037 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004038 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004039
4040 reset: /* we come back here only on syntax errors in interactive shell */
4041
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004042 if (MAYBE_ASSIGNMENT != 0)
4043 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004044 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004045 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004046 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004047 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004048 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004049 int ch;
4050 int next;
4051 int redir_fd;
4052 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004053
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004054 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004055 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004056 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004057 if (ch == EOF) {
4058 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004059
4060 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004061 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004062 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004063 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004064 /* end_trigger == '}' case errors out earlier,
4065 * checking only ')' */
4066 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004067 syntax_error_unterm_ch('(');
4068 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004069 }
4070
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004071 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004072 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004073 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004074 o_free(&dest);
4075 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004076 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004077 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004078 /* (this makes bare "&" cmd a no-op.
4079 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004080 if (pi->num_cmds == 0
4081 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4082 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004083 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004084 pi = NULL;
4085 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004086#if !BB_MMU
4087 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4088 if (pstring)
4089 *pstring = ctx.as_string.data;
4090 else
4091 o_free_unsafe(&ctx.as_string);
4092#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004093 debug_leave();
4094 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004095 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004096 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004097 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004098
4099 next = '\0';
4100 if (ch != '\n')
4101 next = i_peek(input);
4102
4103 is_special = "{}<>;&|()#'" /* special outside of "str" */
4104 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4105 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004106 if (ctx.command->argv /* word [word]{... - non-special */
4107 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004108 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004109 || (next != ';' /* }; - special */
4110 && next != ')' /* }) - special */
4111 && next != '&' /* }& and }&& ... - special */
4112 && next != '|' /* }|| ... - special */
4113 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004114 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004115 ) {
4116 /* They are not special, skip "{}" */
4117 is_special += 2;
4118 }
4119 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004120 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004121
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004122 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004123 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004124 o_addQchr(&dest, ch);
4125 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4126 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004127 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004128 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004129 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004130 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004131 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004132 continue;
4133 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004134
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004135 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004136 if (done_word(&dest, &ctx)) {
4137 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004138 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004139 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004140 /* Is this a case when newline is simply ignored?
4141 * Some examples:
4142 * "cmd | <newline> cmd ..."
4143 * "case ... in <newline> word) ..."
4144 */
4145 if (IS_NULL_CMD(ctx.command)
4146 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004147 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004148 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004149 * Without check #1, interactive shell
4150 * ignores even bare <newline>,
4151 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004152 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004153 * ps2> _ <=== wrong, should be ps1
4154 * Without check #2, "cmd & <newline>"
4155 * is similarly mistreated.
4156 * (BTW, this makes "cmd & cmd"
4157 * and "cmd && cmd" non-orthogonal.
4158 * Really, ask yourself, why
4159 * "cmd && <newline>" doesn't start
4160 * cmd but waits for more input?
4161 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004162 */
4163 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004164 if (pi->num_cmds != 0 /* check #1 */
4165 && pi->followup != PIPE_BG /* check #2 */
4166 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004167 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004168 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004169 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004170 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004171 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004172 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4173 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004174 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004176 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004177 heredoc_cnt = 0;
4178 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004179 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004180 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004181 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004182 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004183 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004184 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004185
4186 /* "cmd}" or "cmd }..." without semicolon or &:
4187 * } is an ordinary char in this case, even inside { cmd; }
4188 * Pathological example: { ""}; } should exec "}" cmd
4189 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004190 if (ch == '}') {
4191 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4192 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004193 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004194 ) {
4195 goto ordinary_char;
4196 }
4197 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4198 goto skip_end_trigger;
4199 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004200 }
4201
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004202 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004203 && (ch != ';' || heredoc_cnt == 0)
4204#if ENABLE_HUSH_CASE
4205 && (ch != ')'
4206 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004207 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004208 )
4209#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004210 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004211 if (heredoc_cnt) {
4212 /* This is technically valid:
4213 * { cat <<HERE; }; echo Ok
4214 * heredoc
4215 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004216 * HERE
4217 * but we don't support this.
4218 * We require heredoc to be in enclosing {}/(),
4219 * if any.
4220 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004221 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004222 goto parse_error;
4223 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004224 if (done_word(&dest, &ctx)) {
4225 goto parse_error;
4226 }
4227 done_pipe(&ctx, PIPE_SEQ);
4228 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004229 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004230 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004231 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004232 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004233 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004234#if !BB_MMU
4235 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4236 if (pstring)
4237 *pstring = ctx.as_string.data;
4238 else
4239 o_free_unsafe(&ctx.as_string);
4240#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004241 debug_leave();
4242 debug_printf_parse("parse_stream return %p: "
4243 "end_trigger char found\n",
4244 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004245 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004246 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004247 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004248 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004249 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004250 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004251
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004252 /* Catch <, > before deciding whether this word is
4253 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4254 switch (ch) {
4255 case '>':
4256 redir_fd = redirect_opt_num(&dest);
4257 if (done_word(&dest, &ctx)) {
4258 goto parse_error;
4259 }
4260 redir_style = REDIRECT_OVERWRITE;
4261 if (next == '>') {
4262 redir_style = REDIRECT_APPEND;
4263 ch = i_getch(input);
4264 nommu_addchr(&ctx.as_string, ch);
4265 }
4266#if 0
4267 else if (next == '(') {
4268 syntax_error(">(process) not supported");
4269 goto parse_error;
4270 }
4271#endif
4272 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4273 goto parse_error;
4274 continue; /* back to top of while (1) */
4275 case '<':
4276 redir_fd = redirect_opt_num(&dest);
4277 if (done_word(&dest, &ctx)) {
4278 goto parse_error;
4279 }
4280 redir_style = REDIRECT_INPUT;
4281 if (next == '<') {
4282 redir_style = REDIRECT_HEREDOC;
4283 heredoc_cnt++;
4284 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4285 ch = i_getch(input);
4286 nommu_addchr(&ctx.as_string, ch);
4287 } else if (next == '>') {
4288 redir_style = REDIRECT_IO;
4289 ch = i_getch(input);
4290 nommu_addchr(&ctx.as_string, ch);
4291 }
4292#if 0
4293 else if (next == '(') {
4294 syntax_error("<(process) not supported");
4295 goto parse_error;
4296 }
4297#endif
4298 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4299 goto parse_error;
4300 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004301 case '#':
4302 if (dest.length == 0 && !dest.has_quoted_part) {
4303 /* skip "#comment" */
4304 while (1) {
4305 ch = i_peek(input);
4306 if (ch == EOF || ch == '\n')
4307 break;
4308 i_getch(input);
4309 /* note: we do not add it to &ctx.as_string */
4310 }
4311 nommu_addchr(&ctx.as_string, '\n');
4312 continue; /* back to top of while (1) */
4313 }
4314 break;
4315 case '\\':
4316 if (next == '\n') {
4317 /* It's "\<newline>" */
4318#if !BB_MMU
4319 /* Remove trailing '\' from ctx.as_string */
4320 ctx.as_string.data[--ctx.as_string.length] = '\0';
4321#endif
4322 ch = i_getch(input); /* eat it */
4323 continue; /* back to top of while (1) */
4324 }
4325 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004326 }
4327
4328 if (dest.o_assignment == MAYBE_ASSIGNMENT
4329 /* check that we are not in word in "a=1 2>word b=1": */
4330 && !ctx.pending_redirect
4331 ) {
4332 /* ch is a special char and thus this word
4333 * cannot be an assignment */
4334 dest.o_assignment = NOT_ASSIGNMENT;
4335 }
4336
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004337 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4338
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004339 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004340 case '#': /* non-comment #: "echo a#b" etc */
4341 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004342 break;
4343 case '\\':
4344 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004345 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004346 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004347 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004348 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004349 /* note: ch != '\n' (that case does not reach this place) */
4350 o_addchr(&dest, '\\');
4351 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4352 o_addchr(&dest, ch);
4353 nommu_addchr(&ctx.as_string, ch);
4354 /* Example: echo Hello \2>file
4355 * we need to know that word 2 is quoted */
4356 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004357 break;
4358 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004359 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004360 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004361 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004362 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004363 }
Eric Andersen25f27032001-04-26 23:22:31 +00004364 break;
4365 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004366 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004367 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004368 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004369 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004370 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004371 goto parse_error;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004372 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004373 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004374 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004375 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004376 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004377 }
Eric Andersen25f27032001-04-26 23:22:31 +00004378 break;
4379 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004380 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004381 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004382 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004383 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004384 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004385 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004386 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004387#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004388 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004389 unsigned pos;
4390
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004391 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4392 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004393 pos = dest.length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004394 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4395 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004396# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004397 o_addstr(&ctx.as_string, dest.data + pos);
4398 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004399# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004400 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4401 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004402 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004403 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004404#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004405 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004406#if ENABLE_HUSH_CASE
4407 case_semi:
4408#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004409 if (done_word(&dest, &ctx)) {
4410 goto parse_error;
4411 }
4412 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004413#if ENABLE_HUSH_CASE
4414 /* Eat multiple semicolons, detect
4415 * whether it means something special */
4416 while (1) {
4417 ch = i_peek(input);
4418 if (ch != ';')
4419 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004420 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004421 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004422 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004423 ctx.ctx_dsemicolon = 1;
4424 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004425 break;
4426 }
4427 }
4428#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004429 new_cmd:
4430 /* We just finished a cmd. New one may start
4431 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004432 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004433 break;
4434 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004435 if (done_word(&dest, &ctx)) {
4436 goto parse_error;
4437 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004438 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004439 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004440 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004441 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004442 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004443 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004444 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004445 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004446 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004447 if (done_word(&dest, &ctx)) {
4448 goto parse_error;
4449 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004450#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004451 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004452 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004453#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004454 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004455 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004456 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004457 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004458 } else {
4459 /* we could pick up a file descriptor choice here
4460 * with redirect_opt_num(), but bash doesn't do it.
4461 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004462 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004463#if !BB_MMU
4464 o_reset_to_empty_unquoted(&ctx.as_string);
4465#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004466 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004467 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004468 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004469#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004470 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004471 if (ctx.ctx_res_w == RES_MATCH
4472 && ctx.command->argv == NULL /* not (word|(... */
4473 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004474 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004475 ) {
4476 continue;
4477 }
4478#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004479 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004480 if (parse_group(&dest, &ctx, input, ch) != 0) {
4481 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004482 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004483 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004484 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004485#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004486 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004487 goto case_semi;
4488#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004489 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004490 /* proper use of this character is caught by end_trigger:
4491 * if we see {, we call parse_group(..., end_trigger='}')
4492 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004493 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004494 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004495 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004496 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004497 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004498 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004499 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004500
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004501 parse_error:
4502 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004503 struct parse_context *pctx;
4504 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004505
4506 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004507 * Sample for finding leaks on syntax error recovery path.
4508 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004509 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004510 * Samples to catch leaks at execution:
4511 * while if (true | {true;}); then echo ok; fi; do break; done
4512 * 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 +00004513 */
4514 pctx = &ctx;
4515 do {
4516 /* Update pipe/command counts,
4517 * otherwise freeing may miss some */
4518 done_pipe(pctx, PIPE_SEQ);
4519 debug_printf_clean("freeing list %p from ctx %p\n",
4520 pctx->list_head, pctx);
4521 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004522 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004523 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004524#if !BB_MMU
4525 o_free_unsafe(&pctx->as_string);
4526#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004527 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004528 if (pctx != &ctx) {
4529 free(pctx);
4530 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004531 IF_HAS_KEYWORDS(pctx = p2;)
4532 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004533 /* Free text, clear all dest fields */
4534 o_free(&dest);
4535 /* If we are not in top-level parse, we return,
4536 * our caller will propagate error.
4537 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004538 if (end_trigger != ';') {
4539#if !BB_MMU
4540 if (pstring)
4541 *pstring = NULL;
4542#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004543 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004544 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004545 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004546 /* Discard cached input, force prompt */
4547 input->p = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004548 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004549 }
Eric Andersen25f27032001-04-26 23:22:31 +00004550}
4551
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004552
4553/*** Execution routines ***/
4554
4555/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004556#if !ENABLE_HUSH_BASH_COMPAT
4557/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4558#define expand_string_to_string(str, do_unbackslash) \
4559 expand_string_to_string(str)
4560#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004561static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004562#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004563static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004564#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004565
4566/* expand_strvec_to_strvec() takes a list of strings, expands
4567 * all variable references within and returns a pointer to
4568 * a list of expanded strings, possibly with larger number
4569 * of strings. (Think VAR="a b"; echo $VAR).
4570 * This new list is allocated as a single malloc block.
4571 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004572 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004573 * Caller can deallocate entire list by single free(list). */
4574
Denys Vlasenko238081f2010-10-03 14:26:26 +02004575/* A horde of its helpers come first: */
4576
4577static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4578{
4579 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004580 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004581
Denys Vlasenko9e800222010-10-03 14:28:04 +02004582#if ENABLE_HUSH_BRACE_EXPANSION
4583 if (c == '{' || c == '}') {
4584 /* { -> \{, } -> \} */
4585 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004586 /* And now we want to add { or } and continue:
4587 * o_addchr(o, c);
4588 * continue;
4589 * luckily, just falling throught achieves this.
4590 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004591 }
4592#endif
4593 o_addchr(o, c);
4594 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004595 /* \z -> \\\z; \<eol> -> \\<eol> */
4596 o_addchr(o, '\\');
4597 if (len) {
4598 len--;
4599 o_addchr(o, '\\');
4600 o_addchr(o, *str++);
4601 }
4602 }
4603 }
4604}
4605
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004606/* Store given string, finalizing the word and starting new one whenever
4607 * we encounter IFS char(s). This is used for expanding variable values.
4608 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4609static int expand_on_ifs(o_string *output, int n, const char *str)
4610{
4611 while (1) {
4612 int word_len = strcspn(str, G.ifs);
4613 if (word_len) {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004614 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004615 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004616 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004617 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004618 * Example: "v='\*'; echo b$v" prints "b\*"
4619 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004620 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004621 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004622 /*/ Why can't we do it easier? */
4623 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4624 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4625 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004626 str += word_len;
4627 }
4628 if (!*str) /* EOL - do not finalize word */
4629 break;
4630 o_addchr(output, '\0');
4631 debug_print_list("expand_on_ifs", output, n);
4632 n = o_save_ptr(output, n);
4633 str += strspn(str, G.ifs); /* skip ifs chars */
4634 }
4635 debug_print_list("expand_on_ifs[1]", output, n);
4636 return n;
4637}
4638
4639/* Helper to expand $((...)) and heredoc body. These act as if
4640 * they are in double quotes, with the exception that they are not :).
4641 * Just the rules are similar: "expand only $var and `cmd`"
4642 *
4643 * Returns malloced string.
4644 * As an optimization, we return NULL if expansion is not needed.
4645 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004646#if !ENABLE_HUSH_BASH_COMPAT
4647/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4648#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4649 encode_then_expand_string(str)
4650#endif
4651static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004652{
4653 char *exp_str;
4654 struct in_str input;
4655 o_string dest = NULL_O_STRING;
4656
4657 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004658 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004659#if ENABLE_HUSH_TICK
4660 && !strchr(str, '`')
4661#endif
4662 ) {
4663 return NULL;
4664 }
4665
4666 /* We need to expand. Example:
4667 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4668 */
4669 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004670 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004671//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004672 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004673 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004674 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4675 o_free_unsafe(&dest);
4676 return exp_str;
4677}
4678
4679#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004680static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004681{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004682 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004683 arith_t res;
4684 char *exp_str;
4685
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004686 math_state.lookupvar = get_local_var_value;
4687 math_state.setvar = set_local_var_from_halves;
4688 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004689 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004690 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004691 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004692 if (errmsg_p)
4693 *errmsg_p = math_state.errmsg;
4694 if (math_state.errmsg)
4695 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004696 return res;
4697}
4698#endif
4699
4700#if ENABLE_HUSH_BASH_COMPAT
4701/* ${var/[/]pattern[/repl]} helpers */
4702static char *strstr_pattern(char *val, const char *pattern, int *size)
4703{
4704 while (1) {
4705 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4706 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4707 if (end) {
4708 *size = end - val;
4709 return val;
4710 }
4711 if (*val == '\0')
4712 return NULL;
4713 /* Optimization: if "*pat" did not match the start of "string",
4714 * we know that "tring", "ring" etc will not match too:
4715 */
4716 if (pattern[0] == '*')
4717 return NULL;
4718 val++;
4719 }
4720}
4721static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4722{
4723 char *result = NULL;
4724 unsigned res_len = 0;
4725 unsigned repl_len = strlen(repl);
4726
4727 while (1) {
4728 int size;
4729 char *s = strstr_pattern(val, pattern, &size);
4730 if (!s)
4731 break;
4732
4733 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4734 memcpy(result + res_len, val, s - val);
4735 res_len += s - val;
4736 strcpy(result + res_len, repl);
4737 res_len += repl_len;
4738 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4739
4740 val = s + size;
4741 if (exp_op == '/')
4742 break;
4743 }
4744 if (val[0] && result) {
4745 result = xrealloc(result, res_len + strlen(val) + 1);
4746 strcpy(result + res_len, val);
4747 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4748 }
4749 debug_printf_varexp("result:'%s'\n", result);
4750 return result;
4751}
4752#endif
4753
4754/* Helper:
4755 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4756 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004757static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004758{
4759 const char *val = NULL;
4760 char *to_be_freed = NULL;
4761 char *p = *pp;
4762 char *var;
4763 char first_char;
4764 char exp_op;
4765 char exp_save = exp_save; /* for compiler */
4766 char *exp_saveptr; /* points to expansion operator */
4767 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004768 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004769
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004770 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004771 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004772 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004773 arg0 = arg[0];
4774 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004775 exp_op = 0;
4776
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004777 if (first_char == '#' /* ${#... */
4778 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4779 ) {
4780 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004781 var++;
4782 exp_op = 'L';
4783 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004784 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004785 if (exp_saveptr /* if 2nd char is one of expansion operators */
4786 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4787 ) {
4788 /* ${?:0}, ${#[:]%0} etc */
4789 exp_saveptr = var + 1;
4790 } else {
4791 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4792 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4793 }
4794 exp_op = exp_save = *exp_saveptr;
4795 if (exp_op) {
4796 exp_word = exp_saveptr + 1;
4797 if (exp_op == ':') {
4798 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004799//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004800 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004801 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004802 ) {
4803 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4804 exp_op = ':';
4805 exp_word--;
4806 }
4807 }
4808 *exp_saveptr = '\0';
4809 } /* else: it's not an expansion op, but bare ${var} */
4810 }
4811
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004812 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004813 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004814 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004815 int n = xatoi_positive(var);
4816 if (n < G.global_argc)
4817 val = G.global_argv[n];
4818 /* else val remains NULL: $N with too big N */
4819 } else {
4820 switch (var[0]) {
4821 case '$': /* pid */
4822 val = utoa(G.root_pid);
4823 break;
4824 case '!': /* bg pid */
4825 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4826 break;
4827 case '?': /* exitcode */
4828 val = utoa(G.last_exitcode);
4829 break;
4830 case '#': /* argc */
4831 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4832 break;
4833 default:
4834 val = get_local_var_value(var);
4835 }
4836 }
4837
4838 /* Handle any expansions */
4839 if (exp_op == 'L') {
4840 debug_printf_expand("expand: length(%s)=", val);
4841 val = utoa(val ? strlen(val) : 0);
4842 debug_printf_expand("%s\n", val);
4843 } else if (exp_op) {
4844 if (exp_op == '%' || exp_op == '#') {
4845 /* Standard-mandated substring removal ops:
4846 * ${parameter%word} - remove smallest suffix pattern
4847 * ${parameter%%word} - remove largest suffix pattern
4848 * ${parameter#word} - remove smallest prefix pattern
4849 * ${parameter##word} - remove largest prefix pattern
4850 *
4851 * Word is expanded to produce a glob pattern.
4852 * Then var's value is matched to it and matching part removed.
4853 */
4854 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004855 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004856 char *exp_exp_word;
4857 char *loc;
4858 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02004859 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004860 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004861 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004862 if (exp_exp_word)
4863 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004864 /* HACK ALERT. We depend here on the fact that
4865 * G.global_argv and results of utoa and get_local_var_value
4866 * are actually in writable memory:
4867 * scan_and_match momentarily stores NULs there. */
4868 t = (char*)val;
4869 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004870 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004871 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004872 free(exp_exp_word);
4873 if (loc) { /* match was found */
4874 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004875 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004876 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004877 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004878 }
4879 }
4880 }
4881#if ENABLE_HUSH_BASH_COMPAT
4882 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004883 /* It's ${var/[/]pattern[/repl]} thing.
4884 * Note that in encoded form it has TWO parts:
4885 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02004886 * and if // is used, it is encoded as \:
4887 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004888 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004889 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004890 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004891 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004892 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004893 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004894 * by the usual expansion rules:
4895 * >az; >bz;
4896 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4897 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4898 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4899 * v='a bz'; echo ${v/a*z/\z} prints "z"
4900 * (note that a*z _pattern_ is never globbed!)
4901 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004902 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004903 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004904 if (!pattern)
4905 pattern = xstrdup(exp_word);
4906 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4907 *p++ = SPECIAL_VAR_SYMBOL;
4908 exp_word = p;
4909 p = strchr(p, SPECIAL_VAR_SYMBOL);
4910 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004911 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004912 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4913 /* HACK ALERT. We depend here on the fact that
4914 * G.global_argv and results of utoa and get_local_var_value
4915 * are actually in writable memory:
4916 * replace_pattern momentarily stores NULs there. */
4917 t = (char*)val;
4918 to_be_freed = replace_pattern(t,
4919 pattern,
4920 (repl ? repl : exp_word),
4921 exp_op);
4922 if (to_be_freed) /* at least one replace happened */
4923 val = to_be_freed;
4924 free(pattern);
4925 free(repl);
4926 }
4927 }
4928#endif
4929 else if (exp_op == ':') {
4930#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4931 /* It's ${var:N[:M]} bashism.
4932 * Note that in encoded form it has TWO parts:
4933 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4934 */
4935 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02004936 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004937
Denys Vlasenko063847d2010-09-15 13:33:02 +02004938 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4939 if (errmsg)
4940 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004941 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4942 *p++ = SPECIAL_VAR_SYMBOL;
4943 exp_word = p;
4944 p = strchr(p, SPECIAL_VAR_SYMBOL);
4945 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02004946 len = expand_and_evaluate_arith(exp_word, &errmsg);
4947 if (errmsg)
4948 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004949 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004950 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004951 if (beg < 0) /* bash compat */
4952 beg = 0;
4953 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004954 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02004955 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02004956 val = NULL;
4957 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004958 /* Paranoia. What if user entered 9999999999999
4959 * which fits in arith_t but not int? */
4960 if (len >= INT_MAX)
4961 len = INT_MAX;
4962 val = to_be_freed = xstrndup(val + beg, len);
4963 }
4964 debug_printf_varexp("val:'%s'\n", val);
4965 } else
4966#endif
4967 {
4968 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004969 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004970 }
4971 } else { /* one of "-=+?" */
4972 /* Standard-mandated substitution ops:
4973 * ${var?word} - indicate error if unset
4974 * If var is unset, word (or a message indicating it is unset
4975 * if word is null) is written to standard error
4976 * and the shell exits with a non-zero exit status.
4977 * Otherwise, the value of var is substituted.
4978 * ${var-word} - use default value
4979 * If var is unset, word is substituted.
4980 * ${var=word} - assign and use default value
4981 * If var is unset, word is assigned to var.
4982 * In all cases, final value of var is substituted.
4983 * ${var+word} - use alternative value
4984 * If var is unset, null is substituted.
4985 * Otherwise, word is substituted.
4986 *
4987 * Word is subjected to tilde expansion, parameter expansion,
4988 * command substitution, and arithmetic expansion.
4989 * If word is not needed, it is not expanded.
4990 *
4991 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4992 * but also treat null var as if it is unset.
4993 */
4994 int use_word = (!val || ((exp_save == ':') && !val[0]));
4995 if (exp_op == '+')
4996 use_word = !use_word;
4997 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4998 (exp_save == ':') ? "true" : "false", use_word);
4999 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005000 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005001 if (to_be_freed)
5002 exp_word = to_be_freed;
5003 if (exp_op == '?') {
5004 /* mimic bash message */
5005 die_if_script("%s: %s",
5006 var,
5007 exp_word[0] ? exp_word : "parameter null or not set"
5008 );
5009//TODO: how interactive bash aborts expansion mid-command?
5010 } else {
5011 val = exp_word;
5012 }
5013
5014 if (exp_op == '=') {
5015 /* ${var=[word]} or ${var:=[word]} */
5016 if (isdigit(var[0]) || var[0] == '#') {
5017 /* mimic bash message */
5018 die_if_script("$%s: cannot assign in this way", var);
5019 val = NULL;
5020 } else {
5021 char *new_var = xasprintf("%s=%s", var, val);
5022 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5023 }
5024 }
5025 }
5026 } /* one of "-=+?" */
5027
5028 *exp_saveptr = exp_save;
5029 } /* if (exp_op) */
5030
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005031 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005032
5033 *pp = p;
5034 *to_be_freed_pp = to_be_freed;
5035 return val;
5036}
5037
5038/* Expand all variable references in given string, adding words to list[]
5039 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5040 * to be filled). This routine is extremely tricky: has to deal with
5041 * variables/parameters with whitespace, $* and $@, and constructs like
5042 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005043static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005044{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005045 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005046 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005047 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005048 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005049 char *p;
5050
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005051 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5052 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005053 debug_print_list("expand_vars_to_list", output, n);
5054 n = o_save_ptr(output, n);
5055 debug_print_list("expand_vars_to_list[0]", output, n);
5056
5057 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5058 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005059 char *to_be_freed = NULL;
5060 const char *val = NULL;
5061#if ENABLE_HUSH_TICK
5062 o_string subst_result = NULL_O_STRING;
5063#endif
5064#if ENABLE_SH_MATH_SUPPORT
5065 char arith_buf[sizeof(arith_t)*3 + 2];
5066#endif
5067 o_addblock(output, arg, p - arg);
5068 debug_print_list("expand_vars_to_list[1]", output, n);
5069 arg = ++p;
5070 p = strchr(p, SPECIAL_VAR_SYMBOL);
5071
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005072 /* Fetch special var name (if it is indeed one of them)
5073 * and quote bit, force the bit on if singleword expansion -
5074 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005075 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005076
5077 /* Is this variable quoted and thus expansion can't be null?
5078 * "$@" is special. Even if quoted, it can still
5079 * expand to nothing (not even an empty string),
5080 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005081 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005082 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005083
5084 switch (first_ch & 0x7f) {
5085 /* Highest bit in first_ch indicates that var is double-quoted */
5086 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005087 case '@': {
5088 int i;
5089 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005090 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005091 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005092 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005093 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005094 while (G.global_argv[i]) {
5095 n = expand_on_ifs(output, n, G.global_argv[i]);
5096 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5097 if (G.global_argv[i++][0] && G.global_argv[i]) {
5098 /* this argv[] is not empty and not last:
5099 * put terminating NUL, start new word */
5100 o_addchr(output, '\0');
5101 debug_print_list("expand_vars_to_list[2]", output, n);
5102 n = o_save_ptr(output, n);
5103 debug_print_list("expand_vars_to_list[3]", output, n);
5104 }
5105 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005106 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005107 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005108 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005109 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005110 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005111 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005112 while (1) {
5113 o_addQstr(output, G.global_argv[i]);
5114 if (++i >= G.global_argc)
5115 break;
5116 o_addchr(output, '\0');
5117 debug_print_list("expand_vars_to_list[4]", output, n);
5118 n = o_save_ptr(output, n);
5119 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005120 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005121 while (1) {
5122 o_addQstr(output, G.global_argv[i]);
5123 if (!G.global_argv[++i])
5124 break;
5125 if (G.ifs[0])
5126 o_addchr(output, G.ifs[0]);
5127 }
5128 }
5129 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005130 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005131 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5132 /* "Empty variable", used to make "" etc to not disappear */
5133 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005134 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005135 break;
5136#if ENABLE_HUSH_TICK
5137 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005138 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005139 arg++;
5140 /* Can't just stuff it into output o_string,
5141 * expanded result may need to be globbed
5142 * and $IFS-splitted */
5143 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5144 G.last_exitcode = process_command_subs(&subst_result, arg);
5145 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5146 val = subst_result.data;
5147 goto store_val;
5148#endif
5149#if ENABLE_SH_MATH_SUPPORT
5150 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5151 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005152
5153 arg++; /* skip '+' */
5154 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5155 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005156 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005157 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5158 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005159 val = arith_buf;
5160 break;
5161 }
5162#endif
5163 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005164 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005165 IF_HUSH_TICK(store_val:)
5166 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005167 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5168 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005169 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005170 n = expand_on_ifs(output, n, val);
5171 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005172 }
5173 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005174 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5175 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005176 }
5177 break;
5178
5179 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5180
5181 if (val && val[0]) {
5182 o_addQstr(output, val);
5183 }
5184 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005185
5186 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5187 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005188 if (*p != SPECIAL_VAR_SYMBOL)
5189 *p = SPECIAL_VAR_SYMBOL;
5190
5191#if ENABLE_HUSH_TICK
5192 o_free(&subst_result);
5193#endif
5194 arg = ++p;
5195 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5196
5197 if (arg[0]) {
5198 debug_print_list("expand_vars_to_list[a]", output, n);
5199 /* this part is literal, and it was already pre-quoted
5200 * if needed (much earlier), do not use o_addQstr here! */
5201 o_addstr_with_NUL(output, arg);
5202 debug_print_list("expand_vars_to_list[b]", output, n);
5203 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005204 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005205 ) {
5206 n--;
5207 /* allow to reuse list[n] later without re-growth */
5208 output->has_empty_slot = 1;
5209 } else {
5210 o_addchr(output, '\0');
5211 }
5212
5213 return n;
5214}
5215
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005216static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005217{
5218 int n;
5219 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005220 o_string output = NULL_O_STRING;
5221
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005222 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005223
5224 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005225 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005226 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005227 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005228 }
5229 debug_print_list("expand_variables", &output, n);
5230
5231 /* output.data (malloced in one block) gets returned in "list" */
5232 list = o_finalize_list(&output, n);
5233 debug_print_strings("expand_variables[1]", list);
5234 return list;
5235}
5236
5237static char **expand_strvec_to_strvec(char **argv)
5238{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005239 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005240}
5241
5242#if ENABLE_HUSH_BASH_COMPAT
5243static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5244{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005245 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005246}
5247#endif
5248
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005249/* Used for expansion of right hand of assignments,
5250 * $((...)), heredocs, variable espansion parts.
5251 *
5252 * NB: should NOT do globbing!
5253 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5254 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005255static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005256{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005257#if !ENABLE_HUSH_BASH_COMPAT
5258 const int do_unbackslash = 1;
5259#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005260 char *argv[2], **list;
5261
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005262 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005263 /* This is generally an optimization, but it also
5264 * handles "", which otherwise trips over !list[0] check below.
5265 * (is this ever happens that we actually get str="" here?)
5266 */
5267 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5268 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005269 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005270 return xstrdup(str);
5271 }
5272
5273 argv[0] = (char*)str;
5274 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005275 list = expand_variables(argv, do_unbackslash
5276 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5277 : EXP_FLAG_SINGLEWORD
5278 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005279 if (HUSH_DEBUG)
5280 if (!list[0] || list[1])
5281 bb_error_msg_and_die("BUG in varexp2");
5282 /* actually, just move string 2*sizeof(char*) bytes back */
5283 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005284 if (do_unbackslash)
5285 unbackslash((char*)list);
5286 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005287 return (char*)list;
5288}
5289
5290/* Used for "eval" builtin */
5291static char* expand_strvec_to_string(char **argv)
5292{
5293 char **list;
5294
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005295 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005296 /* Convert all NULs to spaces */
5297 if (list[0]) {
5298 int n = 1;
5299 while (list[n]) {
5300 if (HUSH_DEBUG)
5301 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5302 bb_error_msg_and_die("BUG in varexp3");
5303 /* bash uses ' ' regardless of $IFS contents */
5304 list[n][-1] = ' ';
5305 n++;
5306 }
5307 }
5308 overlapping_strcpy((char*)list, list[0]);
5309 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5310 return (char*)list;
5311}
5312
5313static char **expand_assignments(char **argv, int count)
5314{
5315 int i;
5316 char **p;
5317
5318 G.expanded_assignments = p = NULL;
5319 /* Expand assignments into one string each */
5320 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005321 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005322 }
5323 G.expanded_assignments = NULL;
5324 return p;
5325}
5326
5327
5328#if BB_MMU
5329/* never called */
5330void re_execute_shell(char ***to_free, const char *s,
5331 char *g_argv0, char **g_argv,
5332 char **builtin_argv) NORETURN;
5333
5334static void reset_traps_to_defaults(void)
5335{
5336 /* This function is always called in a child shell
5337 * after fork (not vfork, NOMMU doesn't use this function).
5338 */
5339 unsigned sig;
5340 unsigned mask;
5341
5342 /* Child shells are not interactive.
5343 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5344 * Testcase: (while :; do :; done) + ^Z should background.
5345 * Same goes for SIGTERM, SIGHUP, SIGINT.
5346 */
5347 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5348 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5349
5350 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5351 * Stupid. It can be done with *single* &= op, but we can't use
5352 * the fact that G.blocked_set is implemented as a bitmask
5353 * in libc... */
5354 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5355 sig = 1;
5356 while (1) {
5357 if (mask & 1) {
5358 /* Careful. Only if no trap or trap is not "" */
5359 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5360 sigdelset(&G.blocked_set, sig);
5361 }
5362 mask >>= 1;
5363 if (!mask)
5364 break;
5365 sig++;
5366 }
5367 /* Our homegrown sig mask is saner to work with :) */
5368 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5369
5370 /* Resetting all traps to default except empty ones */
5371 mask = G.non_DFL_mask;
5372 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5373 if (!G.traps[sig] || !G.traps[sig][0])
5374 continue;
5375 free(G.traps[sig]);
5376 G.traps[sig] = NULL;
5377 /* There is no signal for 0 (EXIT) */
5378 if (sig == 0)
5379 continue;
5380 /* There was a trap handler, we just removed it.
5381 * But if sig still has non-DFL handling,
5382 * we should not unblock the sig. */
5383 if (mask & 1)
5384 continue;
5385 sigdelset(&G.blocked_set, sig);
5386 }
5387 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5388}
5389
5390#else /* !BB_MMU */
5391
5392static void re_execute_shell(char ***to_free, const char *s,
5393 char *g_argv0, char **g_argv,
5394 char **builtin_argv) NORETURN;
5395static void re_execute_shell(char ***to_free, const char *s,
5396 char *g_argv0, char **g_argv,
5397 char **builtin_argv)
5398{
5399# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5400 /* delims + 2 * (number of bytes in printed hex numbers) */
5401 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5402 char *heredoc_argv[4];
5403 struct variable *cur;
5404# if ENABLE_HUSH_FUNCTIONS
5405 struct function *funcp;
5406# endif
5407 char **argv, **pp;
5408 unsigned cnt;
5409 unsigned long long empty_trap_mask;
5410
5411 if (!g_argv0) { /* heredoc */
5412 argv = heredoc_argv;
5413 argv[0] = (char *) G.argv0_for_re_execing;
5414 argv[1] = (char *) "-<";
5415 argv[2] = (char *) s;
5416 argv[3] = NULL;
5417 pp = &argv[3]; /* used as pointer to empty environment */
5418 goto do_exec;
5419 }
5420
5421 cnt = 0;
5422 pp = builtin_argv;
5423 if (pp) while (*pp++)
5424 cnt++;
5425
5426 empty_trap_mask = 0;
5427 if (G.traps) {
5428 int sig;
5429 for (sig = 1; sig < NSIG; sig++) {
5430 if (G.traps[sig] && !G.traps[sig][0])
5431 empty_trap_mask |= 1LL << sig;
5432 }
5433 }
5434
5435 sprintf(param_buf, NOMMU_HACK_FMT
5436 , (unsigned) G.root_pid
5437 , (unsigned) G.root_ppid
5438 , (unsigned) G.last_bg_pid
5439 , (unsigned) G.last_exitcode
5440 , cnt
5441 , empty_trap_mask
5442 IF_HUSH_LOOPS(, G.depth_of_loop)
5443 );
5444# undef NOMMU_HACK_FMT
5445 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5446 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5447 */
5448 cnt += 6;
5449 for (cur = G.top_var; cur; cur = cur->next) {
5450 if (!cur->flg_export || cur->flg_read_only)
5451 cnt += 2;
5452 }
5453# if ENABLE_HUSH_FUNCTIONS
5454 for (funcp = G.top_func; funcp; funcp = funcp->next)
5455 cnt += 3;
5456# endif
5457 pp = g_argv;
5458 while (*pp++)
5459 cnt++;
5460 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5461 *pp++ = (char *) G.argv0_for_re_execing;
5462 *pp++ = param_buf;
5463 for (cur = G.top_var; cur; cur = cur->next) {
5464 if (strcmp(cur->varstr, hush_version_str) == 0)
5465 continue;
5466 if (cur->flg_read_only) {
5467 *pp++ = (char *) "-R";
5468 *pp++ = cur->varstr;
5469 } else if (!cur->flg_export) {
5470 *pp++ = (char *) "-V";
5471 *pp++ = cur->varstr;
5472 }
5473 }
5474# if ENABLE_HUSH_FUNCTIONS
5475 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5476 *pp++ = (char *) "-F";
5477 *pp++ = funcp->name;
5478 *pp++ = funcp->body_as_string;
5479 }
5480# endif
5481 /* We can pass activated traps here. Say, -Tnn:trap_string
5482 *
5483 * However, POSIX says that subshells reset signals with traps
5484 * to SIG_DFL.
5485 * I tested bash-3.2 and it not only does that with true subshells
5486 * of the form ( list ), but with any forked children shells.
5487 * I set trap "echo W" WINCH; and then tried:
5488 *
5489 * { echo 1; sleep 20; echo 2; } &
5490 * while true; do echo 1; sleep 20; echo 2; break; done &
5491 * true | { echo 1; sleep 20; echo 2; } | cat
5492 *
5493 * In all these cases sending SIGWINCH to the child shell
5494 * did not run the trap. If I add trap "echo V" WINCH;
5495 * _inside_ group (just before echo 1), it works.
5496 *
5497 * I conclude it means we don't need to pass active traps here.
5498 * Even if we would use signal handlers instead of signal masking
5499 * in order to implement trap handling,
5500 * exec syscall below resets signals to SIG_DFL for us.
5501 */
5502 *pp++ = (char *) "-c";
5503 *pp++ = (char *) s;
5504 if (builtin_argv) {
5505 while (*++builtin_argv)
5506 *pp++ = *builtin_argv;
5507 *pp++ = (char *) "";
5508 }
5509 *pp++ = g_argv0;
5510 while (*g_argv)
5511 *pp++ = *g_argv++;
5512 /* *pp = NULL; - is already there */
5513 pp = environ;
5514
5515 do_exec:
5516 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5517 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5518 execve(bb_busybox_exec_path, argv, pp);
5519 /* Fallback. Useful for init=/bin/hush usage etc */
5520 if (argv[0][0] == '/')
5521 execve(argv[0], argv, pp);
5522 xfunc_error_retval = 127;
5523 bb_error_msg_and_die("can't re-execute the shell");
5524}
5525#endif /* !BB_MMU */
5526
5527
5528static int run_and_free_list(struct pipe *pi);
5529
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005530/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005531 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5532 * end_trigger controls how often we stop parsing
5533 * NUL: parse all, execute, return
5534 * ';': parse till ';' or newline, execute, repeat till EOF
5535 */
5536static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005537{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005538 /* Why we need empty flag?
5539 * An obscure corner case "false; ``; echo $?":
5540 * empty command in `` should still set $? to 0.
5541 * But we can't just set $? to 0 at the start,
5542 * this breaks "false; echo `echo $?`" case.
5543 */
5544 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005545 while (1) {
5546 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005547
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005548#if ENABLE_HUSH_INTERACTIVE
5549 if (end_trigger == ';')
5550 inp->promptmode = 0; /* PS1 */
5551#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005552 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005553 if (!pipe_list) { /* EOF */
5554 if (empty)
5555 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005556 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005557 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005558 debug_print_tree(pipe_list, 0);
5559 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5560 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005561 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005562#if ENABLE_HUSH_FUNCTIONS
5563 if (G.flag_return_in_progress == 1)
5564 break;
5565#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005566 }
Eric Andersen25f27032001-04-26 23:22:31 +00005567}
5568
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005569static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005570{
5571 struct in_str input;
5572 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005573 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005574}
5575
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005576static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005577{
Eric Andersen25f27032001-04-26 23:22:31 +00005578 struct in_str input;
5579 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005580 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005581}
5582
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005583#if ENABLE_HUSH_TICK
5584static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5585{
5586 pid_t pid;
5587 int channel[2];
5588# if !BB_MMU
5589 char **to_free = NULL;
5590# endif
5591
5592 xpipe(channel);
5593 pid = BB_MMU ? xfork() : xvfork();
5594 if (pid == 0) { /* child */
5595 disable_restore_tty_pgrp_on_exit();
5596 /* Process substitution is not considered to be usual
5597 * 'command execution'.
5598 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5599 */
5600 bb_signals(0
5601 + (1 << SIGTSTP)
5602 + (1 << SIGTTIN)
5603 + (1 << SIGTTOU)
5604 , SIG_IGN);
5605 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5606 close(channel[0]); /* NB: close _first_, then move fd! */
5607 xmove_fd(channel[1], 1);
5608 /* Prevent it from trying to handle ctrl-z etc */
5609 IF_HUSH_JOB(G.run_list_level = 1;)
5610 /* Awful hack for `trap` or $(trap).
5611 *
5612 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5613 * contains an example where "trap" is executed in a subshell:
5614 *
5615 * save_traps=$(trap)
5616 * ...
5617 * eval "$save_traps"
5618 *
5619 * Standard does not say that "trap" in subshell shall print
5620 * parent shell's traps. It only says that its output
5621 * must have suitable form, but then, in the above example
5622 * (which is not supposed to be normative), it implies that.
5623 *
5624 * bash (and probably other shell) does implement it
5625 * (traps are reset to defaults, but "trap" still shows them),
5626 * but as a result, "trap" logic is hopelessly messed up:
5627 *
5628 * # trap
5629 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5630 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5631 * # true | trap <--- trap is in subshell - no output (ditto)
5632 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5633 * trap -- 'echo Ho' SIGWINCH
5634 * # echo `(trap)` <--- in subshell in subshell - output
5635 * trap -- 'echo Ho' SIGWINCH
5636 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5637 * trap -- 'echo Ho' SIGWINCH
5638 *
5639 * The rules when to forget and when to not forget traps
5640 * get really complex and nonsensical.
5641 *
5642 * Our solution: ONLY bare $(trap) or `trap` is special.
5643 */
5644 s = skip_whitespace(s);
5645 if (strncmp(s, "trap", 4) == 0
5646 && skip_whitespace(s + 4)[0] == '\0'
5647 ) {
5648 static const char *const argv[] = { NULL, NULL };
5649 builtin_trap((char**)argv);
5650 exit(0); /* not _exit() - we need to fflush */
5651 }
5652# if BB_MMU
5653 reset_traps_to_defaults();
5654 parse_and_run_string(s);
5655 _exit(G.last_exitcode);
5656# else
5657 /* We re-execute after vfork on NOMMU. This makes this script safe:
5658 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5659 * huge=`cat BIG` # was blocking here forever
5660 * echo OK
5661 */
5662 re_execute_shell(&to_free,
5663 s,
5664 G.global_argv[0],
5665 G.global_argv + 1,
5666 NULL);
5667# endif
5668 }
5669
5670 /* parent */
5671 *pid_p = pid;
5672# if ENABLE_HUSH_FAST
5673 G.count_SIGCHLD++;
5674//bb_error_msg("[%d] fork in generate_stream_from_string:"
5675// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5676// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5677# endif
5678 enable_restore_tty_pgrp_on_exit();
5679# if !BB_MMU
5680 free(to_free);
5681# endif
5682 close(channel[1]);
5683 close_on_exec_on(channel[0]);
5684 return xfdopen_for_read(channel[0]);
5685}
5686
5687/* Return code is exit status of the process that is run. */
5688static int process_command_subs(o_string *dest, const char *s)
5689{
5690 FILE *fp;
5691 struct in_str pipe_str;
5692 pid_t pid;
5693 int status, ch, eol_cnt;
5694
5695 fp = generate_stream_from_string(s, &pid);
5696
5697 /* Now send results of command back into original context */
5698 setup_file_in_str(&pipe_str, fp);
5699 eol_cnt = 0;
5700 while ((ch = i_getch(&pipe_str)) != EOF) {
5701 if (ch == '\n') {
5702 eol_cnt++;
5703 continue;
5704 }
5705 while (eol_cnt) {
5706 o_addchr(dest, '\n');
5707 eol_cnt--;
5708 }
5709 o_addQchr(dest, ch);
5710 }
5711
5712 debug_printf("done reading from `cmd` pipe, closing it\n");
5713 fclose(fp);
5714 /* We need to extract exitcode. Test case
5715 * "true; echo `sleep 1; false` $?"
5716 * should print 1 */
5717 safe_waitpid(pid, &status, 0);
5718 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5719 return WEXITSTATUS(status);
5720}
5721#endif /* ENABLE_HUSH_TICK */
5722
5723
5724static void setup_heredoc(struct redir_struct *redir)
5725{
5726 struct fd_pair pair;
5727 pid_t pid;
5728 int len, written;
5729 /* the _body_ of heredoc (misleading field name) */
5730 const char *heredoc = redir->rd_filename;
5731 char *expanded;
5732#if !BB_MMU
5733 char **to_free;
5734#endif
5735
5736 expanded = NULL;
5737 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005738 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005739 if (expanded)
5740 heredoc = expanded;
5741 }
5742 len = strlen(heredoc);
5743
5744 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5745 xpiped_pair(pair);
5746 xmove_fd(pair.rd, redir->rd_fd);
5747
5748 /* Try writing without forking. Newer kernels have
5749 * dynamically growing pipes. Must use non-blocking write! */
5750 ndelay_on(pair.wr);
5751 while (1) {
5752 written = write(pair.wr, heredoc, len);
5753 if (written <= 0)
5754 break;
5755 len -= written;
5756 if (len == 0) {
5757 close(pair.wr);
5758 free(expanded);
5759 return;
5760 }
5761 heredoc += written;
5762 }
5763 ndelay_off(pair.wr);
5764
5765 /* Okay, pipe buffer was not big enough */
5766 /* Note: we must not create a stray child (bastard? :)
5767 * for the unsuspecting parent process. Child creates a grandchild
5768 * and exits before parent execs the process which consumes heredoc
5769 * (that exec happens after we return from this function) */
5770#if !BB_MMU
5771 to_free = NULL;
5772#endif
5773 pid = xvfork();
5774 if (pid == 0) {
5775 /* child */
5776 disable_restore_tty_pgrp_on_exit();
5777 pid = BB_MMU ? xfork() : xvfork();
5778 if (pid != 0)
5779 _exit(0);
5780 /* grandchild */
5781 close(redir->rd_fd); /* read side of the pipe */
5782#if BB_MMU
5783 full_write(pair.wr, heredoc, len); /* may loop or block */
5784 _exit(0);
5785#else
5786 /* Delegate blocking writes to another process */
5787 xmove_fd(pair.wr, STDOUT_FILENO);
5788 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5789#endif
5790 }
5791 /* parent */
5792#if ENABLE_HUSH_FAST
5793 G.count_SIGCHLD++;
5794//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5795#endif
5796 enable_restore_tty_pgrp_on_exit();
5797#if !BB_MMU
5798 free(to_free);
5799#endif
5800 close(pair.wr);
5801 free(expanded);
5802 wait(NULL); /* wait till child has died */
5803}
5804
5805/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5806 * and stderr if they are redirected. */
5807static int setup_redirects(struct command *prog, int squirrel[])
5808{
5809 int openfd, mode;
5810 struct redir_struct *redir;
5811
5812 for (redir = prog->redirects; redir; redir = redir->next) {
5813 if (redir->rd_type == REDIRECT_HEREDOC2) {
5814 /* rd_fd<<HERE case */
5815 if (squirrel && redir->rd_fd < 3
5816 && squirrel[redir->rd_fd] < 0
5817 ) {
5818 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5819 }
5820 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5821 * of the heredoc */
5822 debug_printf_parse("set heredoc '%s'\n",
5823 redir->rd_filename);
5824 setup_heredoc(redir);
5825 continue;
5826 }
5827
5828 if (redir->rd_dup == REDIRFD_TO_FILE) {
5829 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5830 char *p;
5831 if (redir->rd_filename == NULL) {
5832 /* Something went wrong in the parse.
5833 * Pretend it didn't happen */
5834 bb_error_msg("bug in redirect parse");
5835 continue;
5836 }
5837 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005838 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005839 openfd = open_or_warn(p, mode);
5840 free(p);
5841 if (openfd < 0) {
5842 /* this could get lost if stderr has been redirected, but
5843 * bash and ash both lose it as well (though zsh doesn't!) */
5844//what the above comment tries to say?
5845 return 1;
5846 }
5847 } else {
5848 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5849 openfd = redir->rd_dup;
5850 }
5851
5852 if (openfd != redir->rd_fd) {
5853 if (squirrel && redir->rd_fd < 3
5854 && squirrel[redir->rd_fd] < 0
5855 ) {
5856 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5857 }
5858 if (openfd == REDIRFD_CLOSE) {
5859 /* "n>-" means "close me" */
5860 close(redir->rd_fd);
5861 } else {
5862 xdup2(openfd, redir->rd_fd);
5863 if (redir->rd_dup == REDIRFD_TO_FILE)
5864 close(openfd);
5865 }
5866 }
5867 }
5868 return 0;
5869}
5870
5871static void restore_redirects(int squirrel[])
5872{
5873 int i, fd;
5874 for (i = 0; i < 3; i++) {
5875 fd = squirrel[i];
5876 if (fd != -1) {
5877 /* We simply die on error */
5878 xmove_fd(fd, i);
5879 }
5880 }
5881}
5882
5883static char *find_in_path(const char *arg)
5884{
5885 char *ret = NULL;
5886 const char *PATH = get_local_var_value("PATH");
5887
5888 if (!PATH)
5889 return NULL;
5890
5891 while (1) {
5892 const char *end = strchrnul(PATH, ':');
5893 int sz = end - PATH; /* must be int! */
5894
5895 free(ret);
5896 if (sz != 0) {
5897 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5898 } else {
5899 /* We have xxx::yyyy in $PATH,
5900 * it means "use current dir" */
5901 ret = xstrdup(arg);
5902 }
5903 if (access(ret, F_OK) == 0)
5904 break;
5905
5906 if (*end == '\0') {
5907 free(ret);
5908 return NULL;
5909 }
5910 PATH = end + 1;
5911 }
5912
5913 return ret;
5914}
5915
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005916static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005917 const struct built_in_command *x,
5918 const struct built_in_command *end)
5919{
5920 while (x != end) {
5921 if (strcmp(name, x->b_cmd) != 0) {
5922 x++;
5923 continue;
5924 }
5925 debug_printf_exec("found builtin '%s'\n", name);
5926 return x;
5927 }
5928 return NULL;
5929}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005930static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005931{
5932 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5933}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005934static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005935{
5936 const struct built_in_command *x = find_builtin1(name);
5937 if (x)
5938 return x;
5939 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5940}
5941
5942#if ENABLE_HUSH_FUNCTIONS
5943static struct function **find_function_slot(const char *name)
5944{
5945 struct function **funcpp = &G.top_func;
5946 while (*funcpp) {
5947 if (strcmp(name, (*funcpp)->name) == 0) {
5948 break;
5949 }
5950 funcpp = &(*funcpp)->next;
5951 }
5952 return funcpp;
5953}
5954
5955static const struct function *find_function(const char *name)
5956{
5957 const struct function *funcp = *find_function_slot(name);
5958 if (funcp)
5959 debug_printf_exec("found function '%s'\n", name);
5960 return funcp;
5961}
5962
5963/* Note: takes ownership on name ptr */
5964static struct function *new_function(char *name)
5965{
5966 struct function **funcpp = find_function_slot(name);
5967 struct function *funcp = *funcpp;
5968
5969 if (funcp != NULL) {
5970 struct command *cmd = funcp->parent_cmd;
5971 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5972 if (!cmd) {
5973 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5974 free(funcp->name);
5975 /* Note: if !funcp->body, do not free body_as_string!
5976 * This is a special case of "-F name body" function:
5977 * body_as_string was not malloced! */
5978 if (funcp->body) {
5979 free_pipe_list(funcp->body);
5980# if !BB_MMU
5981 free(funcp->body_as_string);
5982# endif
5983 }
5984 } else {
5985 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5986 cmd->argv[0] = funcp->name;
5987 cmd->group = funcp->body;
5988# if !BB_MMU
5989 cmd->group_as_string = funcp->body_as_string;
5990# endif
5991 }
5992 } else {
5993 debug_printf_exec("remembering new function '%s'\n", name);
5994 funcp = *funcpp = xzalloc(sizeof(*funcp));
5995 /*funcp->next = NULL;*/
5996 }
5997
5998 funcp->name = name;
5999 return funcp;
6000}
6001
6002static void unset_func(const char *name)
6003{
6004 struct function **funcpp = find_function_slot(name);
6005 struct function *funcp = *funcpp;
6006
6007 if (funcp != NULL) {
6008 debug_printf_exec("freeing function '%s'\n", funcp->name);
6009 *funcpp = funcp->next;
6010 /* funcp is unlinked now, deleting it.
6011 * Note: if !funcp->body, the function was created by
6012 * "-F name body", do not free ->body_as_string
6013 * and ->name as they were not malloced. */
6014 if (funcp->body) {
6015 free_pipe_list(funcp->body);
6016 free(funcp->name);
6017# if !BB_MMU
6018 free(funcp->body_as_string);
6019# endif
6020 }
6021 free(funcp);
6022 }
6023}
6024
6025# if BB_MMU
6026#define exec_function(to_free, funcp, argv) \
6027 exec_function(funcp, argv)
6028# endif
6029static void exec_function(char ***to_free,
6030 const struct function *funcp,
6031 char **argv) NORETURN;
6032static void exec_function(char ***to_free,
6033 const struct function *funcp,
6034 char **argv)
6035{
6036# if BB_MMU
6037 int n = 1;
6038
6039 argv[0] = G.global_argv[0];
6040 G.global_argv = argv;
6041 while (*++argv)
6042 n++;
6043 G.global_argc = n;
6044 /* On MMU, funcp->body is always non-NULL */
6045 n = run_list(funcp->body);
6046 fflush_all();
6047 _exit(n);
6048# else
6049 re_execute_shell(to_free,
6050 funcp->body_as_string,
6051 G.global_argv[0],
6052 argv + 1,
6053 NULL);
6054# endif
6055}
6056
6057static int run_function(const struct function *funcp, char **argv)
6058{
6059 int rc;
6060 save_arg_t sv;
6061 smallint sv_flg;
6062
6063 save_and_replace_G_args(&sv, argv);
6064
6065 /* "we are in function, ok to use return" */
6066 sv_flg = G.flag_return_in_progress;
6067 G.flag_return_in_progress = -1;
6068# if ENABLE_HUSH_LOCAL
6069 G.func_nest_level++;
6070# endif
6071
6072 /* On MMU, funcp->body is always non-NULL */
6073# if !BB_MMU
6074 if (!funcp->body) {
6075 /* Function defined by -F */
6076 parse_and_run_string(funcp->body_as_string);
6077 rc = G.last_exitcode;
6078 } else
6079# endif
6080 {
6081 rc = run_list(funcp->body);
6082 }
6083
6084# if ENABLE_HUSH_LOCAL
6085 {
6086 struct variable *var;
6087 struct variable **var_pp;
6088
6089 var_pp = &G.top_var;
6090 while ((var = *var_pp) != NULL) {
6091 if (var->func_nest_level < G.func_nest_level) {
6092 var_pp = &var->next;
6093 continue;
6094 }
6095 /* Unexport */
6096 if (var->flg_export)
6097 bb_unsetenv(var->varstr);
6098 /* Remove from global list */
6099 *var_pp = var->next;
6100 /* Free */
6101 if (!var->max_len)
6102 free(var->varstr);
6103 free(var);
6104 }
6105 G.func_nest_level--;
6106 }
6107# endif
6108 G.flag_return_in_progress = sv_flg;
6109
6110 restore_G_args(&sv, argv);
6111
6112 return rc;
6113}
6114#endif /* ENABLE_HUSH_FUNCTIONS */
6115
6116
6117#if BB_MMU
6118#define exec_builtin(to_free, x, argv) \
6119 exec_builtin(x, argv)
6120#else
6121#define exec_builtin(to_free, x, argv) \
6122 exec_builtin(to_free, argv)
6123#endif
6124static void exec_builtin(char ***to_free,
6125 const struct built_in_command *x,
6126 char **argv) NORETURN;
6127static void exec_builtin(char ***to_free,
6128 const struct built_in_command *x,
6129 char **argv)
6130{
6131#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006132 int rcode;
6133 fflush_all();
6134 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006135 fflush_all();
6136 _exit(rcode);
6137#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006138 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006139 /* On NOMMU, we must never block!
6140 * Example: { sleep 99 | read line; } & echo Ok
6141 */
6142 re_execute_shell(to_free,
6143 argv[0],
6144 G.global_argv[0],
6145 G.global_argv + 1,
6146 argv);
6147#endif
6148}
6149
6150
6151static void execvp_or_die(char **argv) NORETURN;
6152static void execvp_or_die(char **argv)
6153{
6154 debug_printf_exec("execing '%s'\n", argv[0]);
6155 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6156 execvp(argv[0], argv);
6157 bb_perror_msg("can't execute '%s'", argv[0]);
6158 _exit(127); /* bash compat */
6159}
6160
6161#if ENABLE_HUSH_MODE_X
6162static void dump_cmd_in_x_mode(char **argv)
6163{
6164 if (G_x_mode && argv) {
6165 /* We want to output the line in one write op */
6166 char *buf, *p;
6167 int len;
6168 int n;
6169
6170 len = 3;
6171 n = 0;
6172 while (argv[n])
6173 len += strlen(argv[n++]) + 1;
6174 buf = xmalloc(len);
6175 buf[0] = '+';
6176 p = buf + 1;
6177 n = 0;
6178 while (argv[n])
6179 p += sprintf(p, " %s", argv[n++]);
6180 *p++ = '\n';
6181 *p = '\0';
6182 fputs(buf, stderr);
6183 free(buf);
6184 }
6185}
6186#else
6187# define dump_cmd_in_x_mode(argv) ((void)0)
6188#endif
6189
6190#if BB_MMU
6191#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6192 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6193#define pseudo_exec(nommu_save, command, argv_expanded) \
6194 pseudo_exec(command, argv_expanded)
6195#endif
6196
6197/* Called after [v]fork() in run_pipe, or from builtin_exec.
6198 * Never returns.
6199 * Don't exit() here. If you don't exec, use _exit instead.
6200 * The at_exit handlers apparently confuse the calling process,
6201 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6202static void pseudo_exec_argv(nommu_save_t *nommu_save,
6203 char **argv, int assignment_cnt,
6204 char **argv_expanded) NORETURN;
6205static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6206 char **argv, int assignment_cnt,
6207 char **argv_expanded)
6208{
6209 char **new_env;
6210
6211 new_env = expand_assignments(argv, assignment_cnt);
6212 dump_cmd_in_x_mode(new_env);
6213
6214 if (!argv[assignment_cnt]) {
6215 /* Case when we are here: ... | var=val | ...
6216 * (note that we do not exit early, i.e., do not optimize out
6217 * expand_assignments(): think about ... | var=`sleep 1` | ...
6218 */
6219 free_strings(new_env);
6220 _exit(EXIT_SUCCESS);
6221 }
6222
6223#if BB_MMU
6224 set_vars_and_save_old(new_env);
6225 free(new_env); /* optional */
6226 /* we can also destroy set_vars_and_save_old's return value,
6227 * to save memory */
6228#else
6229 nommu_save->new_env = new_env;
6230 nommu_save->old_vars = set_vars_and_save_old(new_env);
6231#endif
6232
6233 if (argv_expanded) {
6234 argv = argv_expanded;
6235 } else {
6236 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6237#if !BB_MMU
6238 nommu_save->argv = argv;
6239#endif
6240 }
6241 dump_cmd_in_x_mode(argv);
6242
6243#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6244 if (strchr(argv[0], '/') != NULL)
6245 goto skip;
6246#endif
6247
6248 /* Check if the command matches any of the builtins.
6249 * Depending on context, this might be redundant. But it's
6250 * easier to waste a few CPU cycles than it is to figure out
6251 * if this is one of those cases.
6252 */
6253 {
6254 /* On NOMMU, it is more expensive to re-execute shell
6255 * just in order to run echo or test builtin.
6256 * It's better to skip it here and run corresponding
6257 * non-builtin later. */
6258 const struct built_in_command *x;
6259 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6260 if (x) {
6261 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6262 }
6263 }
6264#if ENABLE_HUSH_FUNCTIONS
6265 /* Check if the command matches any functions */
6266 {
6267 const struct function *funcp = find_function(argv[0]);
6268 if (funcp) {
6269 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6270 }
6271 }
6272#endif
6273
6274#if ENABLE_FEATURE_SH_STANDALONE
6275 /* Check if the command matches any busybox applets */
6276 {
6277 int a = find_applet_by_name(argv[0]);
6278 if (a >= 0) {
6279# if BB_MMU /* see above why on NOMMU it is not allowed */
6280 if (APPLET_IS_NOEXEC(a)) {
6281 debug_printf_exec("running applet '%s'\n", argv[0]);
6282 run_applet_no_and_exit(a, argv);
6283 }
6284# endif
6285 /* Re-exec ourselves */
6286 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6287 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6288 execv(bb_busybox_exec_path, argv);
6289 /* If they called chroot or otherwise made the binary no longer
6290 * executable, fall through */
6291 }
6292 }
6293#endif
6294
6295#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6296 skip:
6297#endif
6298 execvp_or_die(argv);
6299}
6300
6301/* Called after [v]fork() in run_pipe
6302 */
6303static void pseudo_exec(nommu_save_t *nommu_save,
6304 struct command *command,
6305 char **argv_expanded) NORETURN;
6306static void pseudo_exec(nommu_save_t *nommu_save,
6307 struct command *command,
6308 char **argv_expanded)
6309{
6310 if (command->argv) {
6311 pseudo_exec_argv(nommu_save, command->argv,
6312 command->assignment_cnt, argv_expanded);
6313 }
6314
6315 if (command->group) {
6316 /* Cases when we are here:
6317 * ( list )
6318 * { list } &
6319 * ... | ( list ) | ...
6320 * ... | { list } | ...
6321 */
6322#if BB_MMU
6323 int rcode;
6324 debug_printf_exec("pseudo_exec: run_list\n");
6325 reset_traps_to_defaults();
6326 rcode = run_list(command->group);
6327 /* OK to leak memory by not calling free_pipe_list,
6328 * since this process is about to exit */
6329 _exit(rcode);
6330#else
6331 re_execute_shell(&nommu_save->argv_from_re_execing,
6332 command->group_as_string,
6333 G.global_argv[0],
6334 G.global_argv + 1,
6335 NULL);
6336#endif
6337 }
6338
6339 /* Case when we are here: ... | >file */
6340 debug_printf_exec("pseudo_exec'ed null command\n");
6341 _exit(EXIT_SUCCESS);
6342}
6343
6344#if ENABLE_HUSH_JOB
6345static const char *get_cmdtext(struct pipe *pi)
6346{
6347 char **argv;
6348 char *p;
6349 int len;
6350
6351 /* This is subtle. ->cmdtext is created only on first backgrounding.
6352 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6353 * On subsequent bg argv is trashed, but we won't use it */
6354 if (pi->cmdtext)
6355 return pi->cmdtext;
6356 argv = pi->cmds[0].argv;
6357 if (!argv || !argv[0]) {
6358 pi->cmdtext = xzalloc(1);
6359 return pi->cmdtext;
6360 }
6361
6362 len = 0;
6363 do {
6364 len += strlen(*argv) + 1;
6365 } while (*++argv);
6366 p = xmalloc(len);
6367 pi->cmdtext = p;
6368 argv = pi->cmds[0].argv;
6369 do {
6370 len = strlen(*argv);
6371 memcpy(p, *argv, len);
6372 p += len;
6373 *p++ = ' ';
6374 } while (*++argv);
6375 p[-1] = '\0';
6376 return pi->cmdtext;
6377}
6378
6379static void insert_bg_job(struct pipe *pi)
6380{
6381 struct pipe *job, **jobp;
6382 int i;
6383
6384 /* Linear search for the ID of the job to use */
6385 pi->jobid = 1;
6386 for (job = G.job_list; job; job = job->next)
6387 if (job->jobid >= pi->jobid)
6388 pi->jobid = job->jobid + 1;
6389
6390 /* Add job to the list of running jobs */
6391 jobp = &G.job_list;
6392 while ((job = *jobp) != NULL)
6393 jobp = &job->next;
6394 job = *jobp = xmalloc(sizeof(*job));
6395
6396 *job = *pi; /* physical copy */
6397 job->next = NULL;
6398 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6399 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6400 for (i = 0; i < pi->num_cmds; i++) {
6401 job->cmds[i].pid = pi->cmds[i].pid;
6402 /* all other fields are not used and stay zero */
6403 }
6404 job->cmdtext = xstrdup(get_cmdtext(pi));
6405
6406 if (G_interactive_fd)
6407 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6408 G.last_jobid = job->jobid;
6409}
6410
6411static void remove_bg_job(struct pipe *pi)
6412{
6413 struct pipe *prev_pipe;
6414
6415 if (pi == G.job_list) {
6416 G.job_list = pi->next;
6417 } else {
6418 prev_pipe = G.job_list;
6419 while (prev_pipe->next != pi)
6420 prev_pipe = prev_pipe->next;
6421 prev_pipe->next = pi->next;
6422 }
6423 if (G.job_list)
6424 G.last_jobid = G.job_list->jobid;
6425 else
6426 G.last_jobid = 0;
6427}
6428
6429/* Remove a backgrounded job */
6430static void delete_finished_bg_job(struct pipe *pi)
6431{
6432 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006433 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006434}
6435#endif /* JOB */
6436
6437/* Check to see if any processes have exited -- if they
6438 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006439static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006440{
6441 int attributes;
6442 int status;
6443#if ENABLE_HUSH_JOB
6444 struct pipe *pi;
6445#endif
6446 pid_t childpid;
6447 int rcode = 0;
6448
6449 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6450
6451 attributes = WUNTRACED;
6452 if (fg_pipe == NULL)
6453 attributes |= WNOHANG;
6454
6455 errno = 0;
6456#if ENABLE_HUSH_FAST
6457 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6458//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6459//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6460 /* There was neither fork nor SIGCHLD since last waitpid */
6461 /* Avoid doing waitpid syscall if possible */
6462 if (!G.we_have_children) {
6463 errno = ECHILD;
6464 return -1;
6465 }
6466 if (fg_pipe == NULL) { /* is WNOHANG set? */
6467 /* We have children, but they did not exit
6468 * or stop yet (we saw no SIGCHLD) */
6469 return 0;
6470 }
6471 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6472 }
6473#endif
6474
6475/* Do we do this right?
6476 * bash-3.00# sleep 20 | false
6477 * <ctrl-Z pressed>
6478 * [3]+ Stopped sleep 20 | false
6479 * bash-3.00# echo $?
6480 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6481 * [hush 1.14.0: yes we do it right]
6482 */
6483 wait_more:
6484 while (1) {
6485 int i;
6486 int dead;
6487
6488#if ENABLE_HUSH_FAST
6489 i = G.count_SIGCHLD;
6490#endif
6491 childpid = waitpid(-1, &status, attributes);
6492 if (childpid <= 0) {
6493 if (childpid && errno != ECHILD)
6494 bb_perror_msg("waitpid");
6495#if ENABLE_HUSH_FAST
6496 else { /* Until next SIGCHLD, waitpid's are useless */
6497 G.we_have_children = (childpid == 0);
6498 G.handled_SIGCHLD = i;
6499//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6500 }
6501#endif
6502 break;
6503 }
6504 dead = WIFEXITED(status) || WIFSIGNALED(status);
6505
6506#if DEBUG_JOBS
6507 if (WIFSTOPPED(status))
6508 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6509 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6510 if (WIFSIGNALED(status))
6511 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6512 childpid, WTERMSIG(status), WEXITSTATUS(status));
6513 if (WIFEXITED(status))
6514 debug_printf_jobs("pid %d exited, exitcode %d\n",
6515 childpid, WEXITSTATUS(status));
6516#endif
6517 /* Were we asked to wait for fg pipe? */
6518 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006519 i = fg_pipe->num_cmds;
6520 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006521 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6522 if (fg_pipe->cmds[i].pid != childpid)
6523 continue;
6524 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006525 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006526 fg_pipe->cmds[i].pid = 0;
6527 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006528 ex = WEXITSTATUS(status);
6529 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006530 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006531 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6532 */
6533 if (WIFSIGNALED(status)) {
6534 int sig = WTERMSIG(status);
6535 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006536 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6537 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6538 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006539 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6540 * Maybe we need to use sig | 128? */
6541 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006542 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006543 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006544 } else {
6545 fg_pipe->cmds[i].is_stopped = 1;
6546 fg_pipe->stopped_cmds++;
6547 }
6548 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6549 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006550 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006551 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006552 i = fg_pipe->num_cmds;
6553 while (--i >= 0) {
6554 rcode = fg_pipe->cmds[i].cmd_exitcode;
6555 /* usually last process gives overall exitstatus,
6556 * but with "set -o pipefail", last *failed* process does */
6557 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6558 break;
6559 }
6560 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006561/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6562 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6563 * and "killall -STOP cat" */
6564 if (G_interactive_fd) {
6565#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006566 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006567 insert_bg_job(fg_pipe);
6568#endif
6569 return rcode;
6570 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006571 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006572 return rcode;
6573 }
6574 /* There are still running processes in the fg pipe */
6575 goto wait_more; /* do waitpid again */
6576 }
6577 /* it wasnt fg_pipe, look for process in bg pipes */
6578 }
6579
6580#if ENABLE_HUSH_JOB
6581 /* We asked to wait for bg or orphaned children */
6582 /* No need to remember exitcode in this case */
6583 for (pi = G.job_list; pi; pi = pi->next) {
6584 for (i = 0; i < pi->num_cmds; i++) {
6585 if (pi->cmds[i].pid == childpid)
6586 goto found_pi_and_prognum;
6587 }
6588 }
6589 /* Happens when shell is used as init process (init=/bin/sh) */
6590 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6591 continue; /* do waitpid again */
6592
6593 found_pi_and_prognum:
6594 if (dead) {
6595 /* child exited */
6596 pi->cmds[i].pid = 0;
6597 pi->alive_cmds--;
6598 if (!pi->alive_cmds) {
6599 if (G_interactive_fd)
6600 printf(JOB_STATUS_FORMAT, pi->jobid,
6601 "Done", pi->cmdtext);
6602 delete_finished_bg_job(pi);
6603 }
6604 } else {
6605 /* child stopped */
6606 pi->cmds[i].is_stopped = 1;
6607 pi->stopped_cmds++;
6608 }
6609#endif
6610 } /* while (waitpid succeeds)... */
6611
6612 return rcode;
6613}
6614
6615#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006616static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006617{
6618 pid_t p;
6619 int rcode = checkjobs(fg_pipe);
6620 if (G_saved_tty_pgrp) {
6621 /* Job finished, move the shell to the foreground */
6622 p = getpgrp(); /* our process group id */
6623 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6624 tcsetpgrp(G_interactive_fd, p);
6625 }
6626 return rcode;
6627}
6628#endif
6629
6630/* Start all the jobs, but don't wait for anything to finish.
6631 * See checkjobs().
6632 *
6633 * Return code is normally -1, when the caller has to wait for children
6634 * to finish to determine the exit status of the pipe. If the pipe
6635 * is a simple builtin command, however, the action is done by the
6636 * time run_pipe returns, and the exit code is provided as the
6637 * return value.
6638 *
6639 * Returns -1 only if started some children. IOW: we have to
6640 * mask out retvals of builtins etc with 0xff!
6641 *
6642 * The only case when we do not need to [v]fork is when the pipe
6643 * is single, non-backgrounded, non-subshell command. Examples:
6644 * cmd ; ... { list } ; ...
6645 * cmd && ... { list } && ...
6646 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006647 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006648 * or (if SH_STANDALONE) an applet, and we can run the { list }
6649 * with run_list. If it isn't one of these, we fork and exec cmd.
6650 *
6651 * Cases when we must fork:
6652 * non-single: cmd | cmd
6653 * backgrounded: cmd & { list } &
6654 * subshell: ( list ) [&]
6655 */
6656#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006657#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006658 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6659#endif
6660static int redirect_and_varexp_helper(char ***new_env_p,
6661 struct variable **old_vars_p,
6662 struct command *command,
6663 int squirrel[3],
6664 char **argv_expanded)
6665{
6666 /* setup_redirects acts on file descriptors, not FILEs.
6667 * This is perfect for work that comes after exec().
6668 * Is it really safe for inline use? Experimentally,
6669 * things seem to work. */
6670 int rcode = setup_redirects(command, squirrel);
6671 if (rcode == 0) {
6672 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6673 *new_env_p = new_env;
6674 dump_cmd_in_x_mode(new_env);
6675 dump_cmd_in_x_mode(argv_expanded);
6676 if (old_vars_p)
6677 *old_vars_p = set_vars_and_save_old(new_env);
6678 }
6679 return rcode;
6680}
6681static NOINLINE int run_pipe(struct pipe *pi)
6682{
6683 static const char *const null_ptr = NULL;
6684
6685 int cmd_no;
6686 int next_infd;
6687 struct command *command;
6688 char **argv_expanded;
6689 char **argv;
6690 /* it is not always needed, but we aim to smaller code */
6691 int squirrel[] = { -1, -1, -1 };
6692 int rcode;
6693
6694 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6695 debug_enter();
6696
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006697 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6698 * Result should be 3 lines: q w e, qwe, q w e
6699 */
6700 G.ifs = get_local_var_value("IFS");
6701 if (!G.ifs)
6702 G.ifs = defifs;
6703
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006704 IF_HUSH_JOB(pi->pgrp = -1;)
6705 pi->stopped_cmds = 0;
6706 command = &pi->cmds[0];
6707 argv_expanded = NULL;
6708
6709 if (pi->num_cmds != 1
6710 || pi->followup == PIPE_BG
6711 || command->cmd_type == CMD_SUBSHELL
6712 ) {
6713 goto must_fork;
6714 }
6715
6716 pi->alive_cmds = 1;
6717
6718 debug_printf_exec(": group:%p argv:'%s'\n",
6719 command->group, command->argv ? command->argv[0] : "NONE");
6720
6721 if (command->group) {
6722#if ENABLE_HUSH_FUNCTIONS
6723 if (command->cmd_type == CMD_FUNCDEF) {
6724 /* "executing" func () { list } */
6725 struct function *funcp;
6726
6727 funcp = new_function(command->argv[0]);
6728 /* funcp->name is already set to argv[0] */
6729 funcp->body = command->group;
6730# if !BB_MMU
6731 funcp->body_as_string = command->group_as_string;
6732 command->group_as_string = NULL;
6733# endif
6734 command->group = NULL;
6735 command->argv[0] = NULL;
6736 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6737 funcp->parent_cmd = command;
6738 command->child_func = funcp;
6739
6740 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6741 debug_leave();
6742 return EXIT_SUCCESS;
6743 }
6744#endif
6745 /* { list } */
6746 debug_printf("non-subshell group\n");
6747 rcode = 1; /* exitcode if redir failed */
6748 if (setup_redirects(command, squirrel) == 0) {
6749 debug_printf_exec(": run_list\n");
6750 rcode = run_list(command->group) & 0xff;
6751 }
6752 restore_redirects(squirrel);
6753 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6754 debug_leave();
6755 debug_printf_exec("run_pipe: return %d\n", rcode);
6756 return rcode;
6757 }
6758
6759 argv = command->argv ? command->argv : (char **) &null_ptr;
6760 {
6761 const struct built_in_command *x;
6762#if ENABLE_HUSH_FUNCTIONS
6763 const struct function *funcp;
6764#else
6765 enum { funcp = 0 };
6766#endif
6767 char **new_env = NULL;
6768 struct variable *old_vars = NULL;
6769
6770 if (argv[command->assignment_cnt] == NULL) {
6771 /* Assignments, but no command */
6772 /* Ensure redirects take effect (that is, create files).
6773 * Try "a=t >file" */
6774#if 0 /* A few cases in testsuite fail with this code. FIXME */
6775 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6776 /* Set shell variables */
6777 if (new_env) {
6778 argv = new_env;
6779 while (*argv) {
6780 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6781 /* Do we need to flag set_local_var() errors?
6782 * "assignment to readonly var" and "putenv error"
6783 */
6784 argv++;
6785 }
6786 }
6787 /* Redirect error sets $? to 1. Otherwise,
6788 * if evaluating assignment value set $?, retain it.
6789 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6790 if (rcode == 0)
6791 rcode = G.last_exitcode;
6792 /* Exit, _skipping_ variable restoring code: */
6793 goto clean_up_and_ret0;
6794
6795#else /* Older, bigger, but more correct code */
6796
6797 rcode = setup_redirects(command, squirrel);
6798 restore_redirects(squirrel);
6799 /* Set shell variables */
6800 if (G_x_mode)
6801 bb_putchar_stderr('+');
6802 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006803 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006804 if (G_x_mode)
6805 fprintf(stderr, " %s", p);
6806 debug_printf_exec("set shell var:'%s'->'%s'\n",
6807 *argv, p);
6808 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6809 /* Do we need to flag set_local_var() errors?
6810 * "assignment to readonly var" and "putenv error"
6811 */
6812 argv++;
6813 }
6814 if (G_x_mode)
6815 bb_putchar_stderr('\n');
6816 /* Redirect error sets $? to 1. Otherwise,
6817 * if evaluating assignment value set $?, retain it.
6818 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6819 if (rcode == 0)
6820 rcode = G.last_exitcode;
6821 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6822 debug_leave();
6823 debug_printf_exec("run_pipe: return %d\n", rcode);
6824 return rcode;
6825#endif
6826 }
6827
6828 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006829#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006830 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006831 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006832 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006833#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006834 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006835 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6836 }
6837
6838 /* if someone gives us an empty string: `cmd with empty output` */
6839 if (!argv_expanded[0]) {
6840 free(argv_expanded);
6841 debug_leave();
6842 return G.last_exitcode;
6843 }
6844
6845 x = find_builtin(argv_expanded[0]);
6846#if ENABLE_HUSH_FUNCTIONS
6847 funcp = NULL;
6848 if (!x)
6849 funcp = find_function(argv_expanded[0]);
6850#endif
6851 if (x || funcp) {
6852 if (!funcp) {
6853 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6854 debug_printf("exec with redirects only\n");
6855 rcode = setup_redirects(command, NULL);
6856 goto clean_up_and_ret1;
6857 }
6858 }
6859 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6860 if (rcode == 0) {
6861 if (!funcp) {
6862 debug_printf_exec(": builtin '%s' '%s'...\n",
6863 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006864 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006865 rcode = x->b_function(argv_expanded) & 0xff;
6866 fflush_all();
6867 }
6868#if ENABLE_HUSH_FUNCTIONS
6869 else {
6870# if ENABLE_HUSH_LOCAL
6871 struct variable **sv;
6872 sv = G.shadowed_vars_pp;
6873 G.shadowed_vars_pp = &old_vars;
6874# endif
6875 debug_printf_exec(": function '%s' '%s'...\n",
6876 funcp->name, argv_expanded[1]);
6877 rcode = run_function(funcp, argv_expanded) & 0xff;
6878# if ENABLE_HUSH_LOCAL
6879 G.shadowed_vars_pp = sv;
6880# endif
6881 }
6882#endif
6883 }
6884 clean_up_and_ret:
6885 unset_vars(new_env);
6886 add_vars(old_vars);
6887/* clean_up_and_ret0: */
6888 restore_redirects(squirrel);
6889 clean_up_and_ret1:
6890 free(argv_expanded);
6891 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6892 debug_leave();
6893 debug_printf_exec("run_pipe return %d\n", rcode);
6894 return rcode;
6895 }
6896
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006897 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006898 int n = find_applet_by_name(argv_expanded[0]);
6899 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6900 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6901 if (rcode == 0) {
6902 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6903 argv_expanded[0], argv_expanded[1]);
6904 rcode = run_nofork_applet(n, argv_expanded);
6905 }
6906 goto clean_up_and_ret;
6907 }
6908 }
6909 /* It is neither builtin nor applet. We must fork. */
6910 }
6911
6912 must_fork:
6913 /* NB: argv_expanded may already be created, and that
6914 * might include `cmd` runs! Do not rerun it! We *must*
6915 * use argv_expanded if it's non-NULL */
6916
6917 /* Going to fork a child per each pipe member */
6918 pi->alive_cmds = 0;
6919 next_infd = 0;
6920
6921 cmd_no = 0;
6922 while (cmd_no < pi->num_cmds) {
6923 struct fd_pair pipefds;
6924#if !BB_MMU
6925 volatile nommu_save_t nommu_save;
6926 nommu_save.new_env = NULL;
6927 nommu_save.old_vars = NULL;
6928 nommu_save.argv = NULL;
6929 nommu_save.argv_from_re_execing = NULL;
6930#endif
6931 command = &pi->cmds[cmd_no];
6932 cmd_no++;
6933 if (command->argv) {
6934 debug_printf_exec(": pipe member '%s' '%s'...\n",
6935 command->argv[0], command->argv[1]);
6936 } else {
6937 debug_printf_exec(": pipe member with no argv\n");
6938 }
6939
6940 /* pipes are inserted between pairs of commands */
6941 pipefds.rd = 0;
6942 pipefds.wr = 1;
6943 if (cmd_no < pi->num_cmds)
6944 xpiped_pair(pipefds);
6945
6946 command->pid = BB_MMU ? fork() : vfork();
6947 if (!command->pid) { /* child */
6948#if ENABLE_HUSH_JOB
6949 disable_restore_tty_pgrp_on_exit();
6950 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6951
6952 /* Every child adds itself to new process group
6953 * with pgid == pid_of_first_child_in_pipe */
6954 if (G.run_list_level == 1 && G_interactive_fd) {
6955 pid_t pgrp;
6956 pgrp = pi->pgrp;
6957 if (pgrp < 0) /* true for 1st process only */
6958 pgrp = getpid();
6959 if (setpgid(0, pgrp) == 0
6960 && pi->followup != PIPE_BG
6961 && G_saved_tty_pgrp /* we have ctty */
6962 ) {
6963 /* We do it in *every* child, not just first,
6964 * to avoid races */
6965 tcsetpgrp(G_interactive_fd, pgrp);
6966 }
6967 }
6968#endif
6969 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6970 /* 1st cmd in backgrounded pipe
6971 * should have its stdin /dev/null'ed */
6972 close(0);
6973 if (open(bb_dev_null, O_RDONLY))
6974 xopen("/", O_RDONLY);
6975 } else {
6976 xmove_fd(next_infd, 0);
6977 }
6978 xmove_fd(pipefds.wr, 1);
6979 if (pipefds.rd > 1)
6980 close(pipefds.rd);
6981 /* Like bash, explicit redirects override pipes,
6982 * and the pipe fd is available for dup'ing. */
6983 if (setup_redirects(command, NULL))
6984 _exit(1);
6985
6986 /* Restore default handlers just prior to exec */
6987 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6988
6989 /* Stores to nommu_save list of env vars putenv'ed
6990 * (NOMMU, on MMU we don't need that) */
6991 /* cast away volatility... */
6992 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6993 /* pseudo_exec() does not return */
6994 }
6995
6996 /* parent or error */
6997#if ENABLE_HUSH_FAST
6998 G.count_SIGCHLD++;
6999//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7000#endif
7001 enable_restore_tty_pgrp_on_exit();
7002#if !BB_MMU
7003 /* Clean up after vforked child */
7004 free(nommu_save.argv);
7005 free(nommu_save.argv_from_re_execing);
7006 unset_vars(nommu_save.new_env);
7007 add_vars(nommu_save.old_vars);
7008#endif
7009 free(argv_expanded);
7010 argv_expanded = NULL;
7011 if (command->pid < 0) { /* [v]fork failed */
7012 /* Clearly indicate, was it fork or vfork */
7013 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7014 } else {
7015 pi->alive_cmds++;
7016#if ENABLE_HUSH_JOB
7017 /* Second and next children need to know pid of first one */
7018 if (pi->pgrp < 0)
7019 pi->pgrp = command->pid;
7020#endif
7021 }
7022
7023 if (cmd_no > 1)
7024 close(next_infd);
7025 if (cmd_no < pi->num_cmds)
7026 close(pipefds.wr);
7027 /* Pass read (output) pipe end to next iteration */
7028 next_infd = pipefds.rd;
7029 }
7030
7031 if (!pi->alive_cmds) {
7032 debug_leave();
7033 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7034 return 1;
7035 }
7036
7037 debug_leave();
7038 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7039 return -1;
7040}
7041
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007042/* NB: called by pseudo_exec, and therefore must not modify any
7043 * global data until exec/_exit (we can be a child after vfork!) */
7044static int run_list(struct pipe *pi)
7045{
7046#if ENABLE_HUSH_CASE
7047 char *case_word = NULL;
7048#endif
7049#if ENABLE_HUSH_LOOPS
7050 struct pipe *loop_top = NULL;
7051 char **for_lcur = NULL;
7052 char **for_list = NULL;
7053#endif
7054 smallint last_followup;
7055 smalluint rcode;
7056#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7057 smalluint cond_code = 0;
7058#else
7059 enum { cond_code = 0 };
7060#endif
7061#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007062 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007063 smallint last_rword; /* ditto */
7064#endif
7065
7066 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7067 debug_enter();
7068
7069#if ENABLE_HUSH_LOOPS
7070 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007071 {
7072 struct pipe *cpipe;
7073 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7074 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7075 continue;
7076 /* current word is FOR or IN (BOLD in comments below) */
7077 if (cpipe->next == NULL) {
7078 syntax_error("malformed for");
7079 debug_leave();
7080 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7081 return 1;
7082 }
7083 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7084 if (cpipe->next->res_word == RES_DO)
7085 continue;
7086 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7087 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7088 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7089 ) {
7090 syntax_error("malformed for");
7091 debug_leave();
7092 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7093 return 1;
7094 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007095 }
7096 }
7097#endif
7098
7099 /* Past this point, all code paths should jump to ret: label
7100 * in order to return, no direct "return" statements please.
7101 * This helps to ensure that no memory is leaked. */
7102
7103#if ENABLE_HUSH_JOB
7104 G.run_list_level++;
7105#endif
7106
7107#if HAS_KEYWORDS
7108 rword = RES_NONE;
7109 last_rword = RES_XXXX;
7110#endif
7111 last_followup = PIPE_SEQ;
7112 rcode = G.last_exitcode;
7113
7114 /* Go through list of pipes, (maybe) executing them. */
7115 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7116 if (G.flag_SIGINT)
7117 break;
7118
7119 IF_HAS_KEYWORDS(rword = pi->res_word;)
7120 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7121 rword, cond_code, last_rword);
7122#if ENABLE_HUSH_LOOPS
7123 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7124 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7125 ) {
7126 /* start of a loop: remember where loop starts */
7127 loop_top = pi;
7128 G.depth_of_loop++;
7129 }
7130#endif
7131 /* Still in the same "if...", "then..." or "do..." branch? */
7132 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7133 if ((rcode == 0 && last_followup == PIPE_OR)
7134 || (rcode != 0 && last_followup == PIPE_AND)
7135 ) {
7136 /* It is "<true> || CMD" or "<false> && CMD"
7137 * and we should not execute CMD */
7138 debug_printf_exec("skipped cmd because of || or &&\n");
7139 last_followup = pi->followup;
7140 continue;
7141 }
7142 }
7143 last_followup = pi->followup;
7144 IF_HAS_KEYWORDS(last_rword = rword;)
7145#if ENABLE_HUSH_IF
7146 if (cond_code) {
7147 if (rword == RES_THEN) {
7148 /* if false; then ... fi has exitcode 0! */
7149 G.last_exitcode = rcode = EXIT_SUCCESS;
7150 /* "if <false> THEN cmd": skip cmd */
7151 continue;
7152 }
7153 } else {
7154 if (rword == RES_ELSE || rword == RES_ELIF) {
7155 /* "if <true> then ... ELSE/ELIF cmd":
7156 * skip cmd and all following ones */
7157 break;
7158 }
7159 }
7160#endif
7161#if ENABLE_HUSH_LOOPS
7162 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7163 if (!for_lcur) {
7164 /* first loop through for */
7165
7166 static const char encoded_dollar_at[] ALIGN1 = {
7167 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7168 }; /* encoded representation of "$@" */
7169 static const char *const encoded_dollar_at_argv[] = {
7170 encoded_dollar_at, NULL
7171 }; /* argv list with one element: "$@" */
7172 char **vals;
7173
7174 vals = (char**)encoded_dollar_at_argv;
7175 if (pi->next->res_word == RES_IN) {
7176 /* if no variable values after "in" we skip "for" */
7177 if (!pi->next->cmds[0].argv) {
7178 G.last_exitcode = rcode = EXIT_SUCCESS;
7179 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7180 break;
7181 }
7182 vals = pi->next->cmds[0].argv;
7183 } /* else: "for var; do..." -> assume "$@" list */
7184 /* create list of variable values */
7185 debug_print_strings("for_list made from", vals);
7186 for_list = expand_strvec_to_strvec(vals);
7187 for_lcur = for_list;
7188 debug_print_strings("for_list", for_list);
7189 }
7190 if (!*for_lcur) {
7191 /* "for" loop is over, clean up */
7192 free(for_list);
7193 for_list = NULL;
7194 for_lcur = NULL;
7195 break;
7196 }
7197 /* Insert next value from for_lcur */
7198 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7199 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7200 continue;
7201 }
7202 if (rword == RES_IN) {
7203 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7204 }
7205 if (rword == RES_DONE) {
7206 continue; /* "done" has no cmds too */
7207 }
7208#endif
7209#if ENABLE_HUSH_CASE
7210 if (rword == RES_CASE) {
7211 case_word = expand_strvec_to_string(pi->cmds->argv);
7212 continue;
7213 }
7214 if (rword == RES_MATCH) {
7215 char **argv;
7216
7217 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7218 break;
7219 /* all prev words didn't match, does this one match? */
7220 argv = pi->cmds->argv;
7221 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007222 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007223 /* TODO: which FNM_xxx flags to use? */
7224 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7225 free(pattern);
7226 if (cond_code == 0) { /* match! we will execute this branch */
7227 free(case_word); /* make future "word)" stop */
7228 case_word = NULL;
7229 break;
7230 }
7231 argv++;
7232 }
7233 continue;
7234 }
7235 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7236 if (cond_code != 0)
7237 continue; /* not matched yet, skip this pipe */
7238 }
7239#endif
7240 /* Just pressing <enter> in shell should check for jobs.
7241 * OTOH, in non-interactive shell this is useless
7242 * and only leads to extra job checks */
7243 if (pi->num_cmds == 0) {
7244 if (G_interactive_fd)
7245 goto check_jobs_and_continue;
7246 continue;
7247 }
7248
7249 /* After analyzing all keywords and conditions, we decided
7250 * to execute this pipe. NB: have to do checkjobs(NULL)
7251 * after run_pipe to collect any background children,
7252 * even if list execution is to be stopped. */
7253 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7254 {
7255 int r;
7256#if ENABLE_HUSH_LOOPS
7257 G.flag_break_continue = 0;
7258#endif
7259 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7260 if (r != -1) {
7261 /* We ran a builtin, function, or group.
7262 * rcode is already known
7263 * and we don't need to wait for anything. */
7264 G.last_exitcode = rcode;
7265 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7266 check_and_run_traps(0);
7267#if ENABLE_HUSH_LOOPS
7268 /* Was it "break" or "continue"? */
7269 if (G.flag_break_continue) {
7270 smallint fbc = G.flag_break_continue;
7271 /* We might fall into outer *loop*,
7272 * don't want to break it too */
7273 if (loop_top) {
7274 G.depth_break_continue--;
7275 if (G.depth_break_continue == 0)
7276 G.flag_break_continue = 0;
7277 /* else: e.g. "continue 2" should *break* once, *then* continue */
7278 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7279 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7280 goto check_jobs_and_break;
7281 /* "continue": simulate end of loop */
7282 rword = RES_DONE;
7283 continue;
7284 }
7285#endif
7286#if ENABLE_HUSH_FUNCTIONS
7287 if (G.flag_return_in_progress == 1) {
7288 /* same as "goto check_jobs_and_break" */
7289 checkjobs(NULL);
7290 break;
7291 }
7292#endif
7293 } else if (pi->followup == PIPE_BG) {
7294 /* What does bash do with attempts to background builtins? */
7295 /* even bash 3.2 doesn't do that well with nested bg:
7296 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7297 * I'm NOT treating inner &'s as jobs */
7298 check_and_run_traps(0);
7299#if ENABLE_HUSH_JOB
7300 if (G.run_list_level == 1)
7301 insert_bg_job(pi);
7302#endif
7303 /* Last command's pid goes to $! */
7304 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7305 G.last_exitcode = rcode = EXIT_SUCCESS;
7306 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7307 } else {
7308#if ENABLE_HUSH_JOB
7309 if (G.run_list_level == 1 && G_interactive_fd) {
7310 /* Waits for completion, then fg's main shell */
7311 rcode = checkjobs_and_fg_shell(pi);
7312 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7313 check_and_run_traps(0);
7314 } else
7315#endif
7316 { /* This one just waits for completion */
7317 rcode = checkjobs(pi);
7318 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7319 check_and_run_traps(0);
7320 }
7321 G.last_exitcode = rcode;
7322 }
7323 }
7324
7325 /* Analyze how result affects subsequent commands */
7326#if ENABLE_HUSH_IF
7327 if (rword == RES_IF || rword == RES_ELIF)
7328 cond_code = rcode;
7329#endif
7330#if ENABLE_HUSH_LOOPS
7331 /* Beware of "while false; true; do ..."! */
7332 if (pi->next && pi->next->res_word == RES_DO) {
7333 if (rword == RES_WHILE) {
7334 if (rcode) {
7335 /* "while false; do...done" - exitcode 0 */
7336 G.last_exitcode = rcode = EXIT_SUCCESS;
7337 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7338 goto check_jobs_and_break;
7339 }
7340 }
7341 if (rword == RES_UNTIL) {
7342 if (!rcode) {
7343 debug_printf_exec(": until expr is true: breaking\n");
7344 check_jobs_and_break:
7345 checkjobs(NULL);
7346 break;
7347 }
7348 }
7349 }
7350#endif
7351
7352 check_jobs_and_continue:
7353 checkjobs(NULL);
7354 } /* for (pi) */
7355
7356#if ENABLE_HUSH_JOB
7357 G.run_list_level--;
7358#endif
7359#if ENABLE_HUSH_LOOPS
7360 if (loop_top)
7361 G.depth_of_loop--;
7362 free(for_list);
7363#endif
7364#if ENABLE_HUSH_CASE
7365 free(case_word);
7366#endif
7367 debug_leave();
7368 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7369 return rcode;
7370}
7371
7372/* Select which version we will use */
7373static int run_and_free_list(struct pipe *pi)
7374{
7375 int rcode = 0;
7376 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007377 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007378 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7379 rcode = run_list(pi);
7380 }
7381 /* free_pipe_list has the side effect of clearing memory.
7382 * In the long run that function can be merged with run_list,
7383 * but doing that now would hobble the debugging effort. */
7384 free_pipe_list(pi);
7385 debug_printf_exec("run_and_free_list return %d\n", rcode);
7386 return rcode;
7387}
7388
7389
Denis Vlasenkof9375282009-04-05 19:13:39 +00007390/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007391static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007392{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007393 unsigned sig;
7394 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007395 sigset_t old_blocked_set;
7396
7397 if (!G.inherited_set_is_saved) {
7398 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7399 G.inherited_set = G.blocked_set;
7400 }
7401 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007402
Denis Vlasenkof9375282009-04-05 19:13:39 +00007403 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007404 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007405 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007406 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007407 mask |= SPECIAL_JOB_SIGS;
7408 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007409 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007410
Denis Vlasenkof9375282009-04-05 19:13:39 +00007411 sig = 0;
7412 while (mask) {
7413 if (mask & 1)
7414 sigaddset(&G.blocked_set, sig);
7415 mask >>= 1;
7416 sig++;
7417 }
7418 sigdelset(&G.blocked_set, SIGCHLD);
7419
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007420 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7421 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7422
Denis Vlasenkof9375282009-04-05 19:13:39 +00007423 /* POSIX allows shell to re-enable SIGCHLD
7424 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007425#if ENABLE_HUSH_FAST
7426 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007427 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007428 signal(SIGCHLD, SIGCHLD_handler);
7429#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007430 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007431 signal(SIGCHLD, SIG_DFL);
7432#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007433
7434 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007435}
7436
7437#if ENABLE_HUSH_JOB
7438/* helper */
7439static void maybe_set_to_sigexit(int sig)
7440{
7441 void (*handler)(int);
7442 /* non_DFL_mask'ed signals are, well, masked,
7443 * no need to set handler for them.
7444 */
7445 if (!((G.non_DFL_mask >> sig) & 1)) {
7446 handler = signal(sig, sigexit);
7447 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7448 signal(sig, handler);
7449 }
7450}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007451/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007452static void set_fatal_handlers(void)
7453{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007454 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007455 if (HUSH_DEBUG) {
7456 maybe_set_to_sigexit(SIGILL );
7457 maybe_set_to_sigexit(SIGFPE );
7458 maybe_set_to_sigexit(SIGBUS );
7459 maybe_set_to_sigexit(SIGSEGV);
7460 maybe_set_to_sigexit(SIGTRAP);
7461 } /* else: hush is perfect. what SEGV? */
7462 maybe_set_to_sigexit(SIGABRT);
7463 /* bash 3.2 seems to handle these just like 'fatal' ones */
7464 maybe_set_to_sigexit(SIGPIPE);
7465 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007466 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007467 * if we aren't interactive... but in this case
7468 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007469 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007470 /*maybe_set_to_sigexit(SIGTERM);*/
7471 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007472}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007473#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007474
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007475static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007476{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007477 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007478 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007479 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007480 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007481 break;
7482 case 'x':
7483 IF_HUSH_MODE_X(G_x_mode = state;)
7484 break;
7485 case 'o':
7486 if (!o_opt) {
7487 /* "set -+o" without parameter.
7488 * in bash, set -o produces this output:
7489 * pipefail off
7490 * and set +o:
7491 * set +o pipefail
7492 * We always use the second form.
7493 */
7494 const char *p = o_opt_strings;
7495 idx = 0;
7496 while (*p) {
7497 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7498 idx++;
7499 p += strlen(p) + 1;
7500 }
7501 break;
7502 }
7503 idx = index_in_strings(o_opt_strings, o_opt);
7504 if (idx >= 0) {
7505 G.o_opt[idx] = state;
7506 break;
7507 }
7508 default:
7509 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007510 }
7511 return EXIT_SUCCESS;
7512}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007513
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007514int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007515int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007516{
7517 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007518 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007519 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007520 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007521 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007522
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007523 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007524 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007525 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007526#if !BB_MMU
7527 G.argv0_for_re_execing = argv[0];
7528#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007529 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007530 shell_ver = xzalloc(sizeof(*shell_ver));
7531 shell_ver->flg_export = 1;
7532 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007533 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007534 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007535 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007536 /* Create shell local variables from the values
7537 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007538 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007539 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007540 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007541 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007542 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007543 if (e) while (*e) {
7544 char *value = strchr(*e, '=');
7545 if (value) { /* paranoia */
7546 cur_var->next = xzalloc(sizeof(*cur_var));
7547 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007548 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007549 cur_var->max_len = strlen(*e);
7550 cur_var->flg_export = 1;
7551 }
7552 e++;
7553 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007554 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007555 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7556 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007557
7558 /* Export PWD */
7559 set_pwd_var(/*exp:*/ 1);
7560 /* bash also exports SHLVL and _,
7561 * and sets (but doesn't export) the following variables:
7562 * BASH=/bin/bash
7563 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7564 * BASH_VERSION='3.2.0(1)-release'
7565 * HOSTTYPE=i386
7566 * MACHTYPE=i386-pc-linux-gnu
7567 * OSTYPE=linux-gnu
7568 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007569 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007570 * EUID=<NNNNN>
7571 * UID=<NNNNN>
7572 * GROUPS=()
7573 * LINES=<NNN>
7574 * COLUMNS=<NNN>
7575 * BASH_ARGC=()
7576 * BASH_ARGV=()
7577 * BASH_LINENO=()
7578 * BASH_SOURCE=()
7579 * DIRSTACK=()
7580 * PIPESTATUS=([0]="0")
7581 * HISTFILE=/<xxx>/.bash_history
7582 * HISTFILESIZE=500
7583 * HISTSIZE=500
7584 * MAILCHECK=60
7585 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7586 * SHELL=/bin/bash
7587 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7588 * TERM=dumb
7589 * OPTERR=1
7590 * OPTIND=1
7591 * IFS=$' \t\n'
7592 * PS1='\s-\v\$ '
7593 * PS2='> '
7594 * PS4='+ '
7595 */
7596
Denis Vlasenko38f63192007-01-22 09:03:07 +00007597#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007598 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007599# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7600 {
7601 const char *hp = get_local_var_value("HISTFILE");
7602 if (!hp) {
7603 hp = get_local_var_value("HOME");
7604 if (hp) {
7605 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7606 //set_local_var(xasprintf("HISTFILE=%s", ...));
7607 }
7608 }
7609 }
7610# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007611#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007612
Denis Vlasenko87a86552008-07-29 19:43:10 +00007613 G.global_argc = argc;
7614 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007615 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007616 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007617
Denis Vlasenkoed782372009-04-10 00:45:02 +00007618 if (setjmp(die_jmp)) {
7619 /* xfunc has failed! die die die */
7620 /* no EXIT traps, this is an escape hatch! */
7621 G.exiting = 1;
7622 hush_exit(xfunc_error_retval);
7623 }
7624
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007625 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007626 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007627 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007628 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007629 * in order to intercept (more) signals.
7630 */
7631
7632 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007633 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007634 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007635 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007636 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007637#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007638 "<:$:R:V:"
7639# if ENABLE_HUSH_FUNCTIONS
7640 "F:"
7641# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007642#endif
7643 );
7644 if (opt <= 0)
7645 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007646 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007647 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007648 /* Possibilities:
7649 * sh ... -c 'script'
7650 * sh ... -c 'script' ARG0 [ARG1...]
7651 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007652 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007653 * "" needs to be replaced with NULL
7654 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007655 * Note: the form without ARG0 never happens:
7656 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007657 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007658 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007659 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007660 G.root_ppid = getppid();
7661 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007662 G.global_argv = argv + optind;
7663 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007664 if (builtin_argc) {
7665 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7666 const struct built_in_command *x;
7667
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007668 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007669 x = find_builtin(optarg);
7670 if (x) { /* paranoia */
7671 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7672 G.global_argv += builtin_argc;
7673 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007674 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007675 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007676 }
7677 goto final_return;
7678 }
7679 if (!G.global_argv[0]) {
7680 /* -c 'script' (no params): prevent empty $0 */
7681 G.global_argv--; /* points to argv[i] of 'script' */
7682 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007683 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007684 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007685 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007686 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007687 goto final_return;
7688 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007689 /* Well, we cannot just declare interactiveness,
7690 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007691 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007692 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007693 case 's':
7694 /* "-s" means "read from stdin", but this is how we always
7695 * operate, so simply do nothing here. */
7696 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007697#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007698 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007699 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007700 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007701 case '$': {
7702 unsigned long long empty_trap_mask;
7703
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007704 G.root_pid = bb_strtou(optarg, &optarg, 16);
7705 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007706 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7707 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007708 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7709 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007710 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007711 optarg++;
7712 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007713 optarg++;
7714 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7715 if (empty_trap_mask != 0) {
7716 int sig;
7717 init_sigmasks();
7718 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7719 for (sig = 1; sig < NSIG; sig++) {
7720 if (empty_trap_mask & (1LL << sig)) {
7721 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7722 sigaddset(&G.blocked_set, sig);
7723 }
7724 }
7725 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7726 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007727# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007728 optarg++;
7729 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007730# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007731 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007732 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007733 case 'R':
7734 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007735 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007736 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007737# if ENABLE_HUSH_FUNCTIONS
7738 case 'F': {
7739 struct function *funcp = new_function(optarg);
7740 /* funcp->name is already set to optarg */
7741 /* funcp->body is set to NULL. It's a special case. */
7742 funcp->body_as_string = argv[optind];
7743 optind++;
7744 break;
7745 }
7746# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007747#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007748 case 'n':
7749 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007750 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007751 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007752 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007753#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007754 fprintf(stderr, "Usage: sh [FILE]...\n"
7755 " or: sh -c command [args]...\n\n");
7756 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007757#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007758 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007759#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007760 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007761 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007762
Denys Vlasenkodea47882009-10-09 15:40:49 +02007763 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007764 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007765 G.root_ppid = getppid();
7766 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007767
7768 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007769 if (argv[0] && argv[0][0] == '-') {
7770 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007771 debug_printf("sourcing /etc/profile\n");
7772 input = fopen_for_read("/etc/profile");
7773 if (input != NULL) {
7774 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007775 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007776 parse_and_run_file(input);
7777 fclose(input);
7778 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007779 /* bash: after sourcing /etc/profile,
7780 * tries to source (in the given order):
7781 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007782 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007783 * bash also sources ~/.bash_logout on exit.
7784 * If called as sh, skips .bash_XXX files.
7785 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007786 }
7787
Denis Vlasenkof9375282009-04-05 19:13:39 +00007788 if (argv[optind]) {
7789 FILE *input;
7790 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007791 * "bash <script>" (which is never interactive (unless -i?))
7792 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007793 * If called as sh, does the same but with $ENV.
7794 */
7795 debug_printf("running script '%s'\n", argv[optind]);
7796 G.global_argv = argv + optind;
7797 G.global_argc = argc - optind;
7798 input = xfopen_for_read(argv[optind]);
7799 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007800 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007801 parse_and_run_file(input);
7802#if ENABLE_FEATURE_CLEAN_UP
7803 fclose(input);
7804#endif
7805 goto final_return;
7806 }
7807
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007808 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007809 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007810 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007811
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007812 /* A shell is interactive if the '-i' flag was given,
7813 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007814 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007815 * no arguments remaining or the -s flag given
7816 * standard input is a terminal
7817 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007818 * Refer to Posix.2, the description of the 'sh' utility.
7819 */
7820#if ENABLE_HUSH_JOB
7821 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007822 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7823 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7824 if (G_saved_tty_pgrp < 0)
7825 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007826
7827 /* try to dup stdin to high fd#, >= 255 */
7828 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7829 if (G_interactive_fd < 0) {
7830 /* try to dup to any fd */
7831 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007832 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007833 /* give up */
7834 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007835 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007836 }
7837 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007838// TODO: track & disallow any attempts of user
7839// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007840 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007841 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007842 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007843 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007844
Mike Frysinger38478a62009-05-20 04:48:06 -04007845 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007846 /* If we were run as 'hush &', sleep until we are
7847 * in the foreground (tty pgrp == our pgrp).
7848 * If we get started under a job aware app (like bash),
7849 * make sure we are now in charge so we don't fight over
7850 * who gets the foreground */
7851 while (1) {
7852 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007853 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7854 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007855 break;
7856 /* send TTIN to ourself (should stop us) */
7857 kill(- shell_pgrp, SIGTTIN);
7858 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007859 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007860
Denis Vlasenkof9375282009-04-05 19:13:39 +00007861 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007862 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007863
Mike Frysinger38478a62009-05-20 04:48:06 -04007864 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007865 /* Set other signals to restore saved_tty_pgrp */
7866 set_fatal_handlers();
7867 /* Put ourselves in our own process group
7868 * (bash, too, does this only if ctty is available) */
7869 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7870 /* Grab control of the terminal */
7871 tcsetpgrp(G_interactive_fd, getpid());
7872 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007873 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007874 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007875 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007876 } else {
7877 init_sigmasks();
7878 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007879#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007880 /* No job control compiled in, only prompt/line editing */
7881 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007882 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7883 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007884 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007885 G_interactive_fd = dup(STDIN_FILENO);
7886 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007887 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007888 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007889 }
7890 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007891 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007892 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007893 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007894 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007895#else
7896 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007897 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007898#endif
7899 /* bash:
7900 * if interactive but not a login shell, sources ~/.bashrc
7901 * (--norc turns this off, --rcfile <file> overrides)
7902 */
7903
7904 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007905 /* note: ash and hush share this string */
7906 printf("\n\n%s %s\n"
7907 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7908 "\n",
7909 bb_banner,
7910 "hush - the humble shell"
7911 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007912 }
7913
Denis Vlasenkof9375282009-04-05 19:13:39 +00007914 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007915
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007916 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007917 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007918}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007919
7920
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007921#if ENABLE_MSH
7922int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7923int msh_main(int argc, char **argv)
7924{
7925 //bb_error_msg("msh is deprecated, please use hush instead");
7926 return hush_main(argc, argv);
7927}
7928#endif
7929
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007930
7931/*
7932 * Built-ins
7933 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007934static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007935{
7936 return 0;
7937}
7938
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007939static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007940{
7941 int argc = 0;
7942 while (*argv) {
7943 argc++;
7944 argv++;
7945 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007946 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007947}
7948
7949static int FAST_FUNC builtin_test(char **argv)
7950{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007951 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007952}
7953
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007954static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007955{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007956 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007957}
7958
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007959#if ENABLE_PRINTF
7960static int FAST_FUNC builtin_printf(char **argv)
7961{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007962 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007963}
7964#endif
7965
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007966static char **skip_dash_dash(char **argv)
7967{
7968 argv++;
7969 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7970 argv++;
7971 return argv;
7972}
7973
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007974static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007975{
7976 int rcode = EXIT_SUCCESS;
7977
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007978 argv = skip_dash_dash(argv);
7979 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007980 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007981 /* bash:
7982 * eval "echo Hi; done" ("done" is syntax error):
7983 * "echo Hi" will not execute too.
7984 */
7985 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007986 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007987 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007988 }
7989 return rcode;
7990}
7991
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007992static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007993{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007994 const char *newdir;
7995
7996 argv = skip_dash_dash(argv);
7997 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007998 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007999 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008000 * bash says "bash: cd: HOME not set" and does nothing
8001 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008002 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008003 const char *home = get_local_var_value("HOME");
8004 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008005 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008006 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008007 /* Mimic bash message exactly */
8008 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008009 return EXIT_FAILURE;
8010 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008011 /* Read current dir (get_cwd(1) is inside) and set PWD.
8012 * Note: do not enforce exporting. If PWD was unset or unexported,
8013 * set it again, but do not export. bash does the same.
8014 */
8015 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008016 return EXIT_SUCCESS;
8017}
8018
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008019static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008020{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008021 argv = skip_dash_dash(argv);
8022 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008023 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008024
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008025 /* Careful: we can end up here after [v]fork. Do not restore
8026 * tty pgrp then, only top-level shell process does that */
8027 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8028 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8029
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008030 /* TODO: if exec fails, bash does NOT exit! We do.
8031 * We'll need to undo sigprocmask (it's inside execvp_or_die)
8032 * and tcsetpgrp, and this is inherently racy.
8033 */
8034 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008035}
8036
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008037static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008038{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008039 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008040
8041 /* interactive bash:
8042 * # trap "echo EEE" EXIT
8043 * # exit
8044 * exit
8045 * There are stopped jobs.
8046 * (if there are _stopped_ jobs, running ones don't count)
8047 * # exit
8048 * exit
8049 # EEE (then bash exits)
8050 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008051 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008052 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008053
8054 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008055 argv = skip_dash_dash(argv);
8056 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008057 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008058 /* mimic bash: exit 123abc == exit 255 + error msg */
8059 xfunc_error_retval = 255;
8060 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008061 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008062}
8063
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008064static void print_escaped(const char *s)
8065{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008066 if (*s == '\'')
8067 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008068 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008069 const char *p = strchrnul(s, '\'');
8070 /* print 'xxxx', possibly just '' */
8071 printf("'%.*s'", (int)(p - s), s);
8072 if (*p == '\0')
8073 break;
8074 s = p;
8075 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008076 /* s points to '; print "'''...'''" */
8077 putchar('"');
8078 do putchar('\''); while (*++s == '\'');
8079 putchar('"');
8080 } while (*s);
8081}
8082
Denys Vlasenko295fef82009-06-03 12:47:26 +02008083#if !ENABLE_HUSH_LOCAL
8084#define helper_export_local(argv, exp, lvl) \
8085 helper_export_local(argv, exp)
8086#endif
8087static void helper_export_local(char **argv, int exp, int lvl)
8088{
8089 do {
8090 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008091 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008092
8093 /* So far we do not check that name is valid (TODO?) */
8094
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008095 if (*name_end == '\0') {
8096 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008097
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008098 vpp = get_ptr_to_local_var(name, name_end - name);
8099 var = vpp ? *vpp : NULL;
8100
Denys Vlasenko295fef82009-06-03 12:47:26 +02008101 if (exp == -1) { /* unexporting? */
8102 /* export -n NAME (without =VALUE) */
8103 if (var) {
8104 var->flg_export = 0;
8105 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8106 unsetenv(name);
8107 } /* else: export -n NOT_EXISTING_VAR: no-op */
8108 continue;
8109 }
8110 if (exp == 1) { /* exporting? */
8111 /* export NAME (without =VALUE) */
8112 if (var) {
8113 var->flg_export = 1;
8114 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8115 putenv(var->varstr);
8116 continue;
8117 }
8118 }
8119 /* Exporting non-existing variable.
8120 * bash does not put it in environment,
8121 * but remembers that it is exported,
8122 * and does put it in env when it is set later.
8123 * We just set it to "" and export. */
8124 /* Or, it's "local NAME" (without =VALUE).
8125 * bash sets the value to "". */
8126 name = xasprintf("%s=", name);
8127 } else {
8128 /* (Un)exporting/making local NAME=VALUE */
8129 name = xstrdup(name);
8130 }
8131 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8132 } while (*++argv);
8133}
8134
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008135static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008136{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008137 unsigned opt_unexport;
8138
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008139#if ENABLE_HUSH_EXPORT_N
8140 /* "!": do not abort on errors */
8141 opt_unexport = getopt32(argv, "!n");
8142 if (opt_unexport == (uint32_t)-1)
8143 return EXIT_FAILURE;
8144 argv += optind;
8145#else
8146 opt_unexport = 0;
8147 argv++;
8148#endif
8149
8150 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008151 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008152 if (e) {
8153 while (*e) {
8154#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008155 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008156#else
8157 /* ash emits: export VAR='VAL'
8158 * bash: declare -x VAR="VAL"
8159 * we follow ash example */
8160 const char *s = *e++;
8161 const char *p = strchr(s, '=');
8162
8163 if (!p) /* wtf? take next variable */
8164 continue;
8165 /* export var= */
8166 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008167 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008168 putchar('\n');
8169#endif
8170 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008171 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008172 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008173 return EXIT_SUCCESS;
8174 }
8175
Denys Vlasenko295fef82009-06-03 12:47:26 +02008176 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008177
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008178 return EXIT_SUCCESS;
8179}
8180
Denys Vlasenko295fef82009-06-03 12:47:26 +02008181#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008182static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008183{
8184 if (G.func_nest_level == 0) {
8185 bb_error_msg("%s: not in a function", argv[0]);
8186 return EXIT_FAILURE; /* bash compat */
8187 }
8188 helper_export_local(argv, 0, G.func_nest_level);
8189 return EXIT_SUCCESS;
8190}
8191#endif
8192
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008193static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008194{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008195 int sig;
8196 char *new_cmd;
8197
8198 if (!G.traps)
8199 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8200
8201 argv++;
8202 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008203 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008204 /* No args: print all trapped */
8205 for (i = 0; i < NSIG; ++i) {
8206 if (G.traps[i]) {
8207 printf("trap -- ");
8208 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008209 /* note: bash adds "SIG", but only if invoked
8210 * as "bash". If called as "sh", or if set -o posix,
8211 * then it prints short signal names.
8212 * We are printing short names: */
8213 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008214 }
8215 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008216 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008217 return EXIT_SUCCESS;
8218 }
8219
8220 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008221 /* If first arg is a number: reset all specified signals */
8222 sig = bb_strtou(*argv, NULL, 10);
8223 if (errno == 0) {
8224 int ret;
8225 process_sig_list:
8226 ret = EXIT_SUCCESS;
8227 while (*argv) {
8228 sig = get_signum(*argv++);
8229 if (sig < 0 || sig >= NSIG) {
8230 ret = EXIT_FAILURE;
8231 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008232 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008233 continue;
8234 }
8235
8236 free(G.traps[sig]);
8237 G.traps[sig] = xstrdup(new_cmd);
8238
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008239 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008240 get_signame(sig), sig, G.traps[sig]);
8241
8242 /* There is no signal for 0 (EXIT) */
8243 if (sig == 0)
8244 continue;
8245
8246 if (new_cmd) {
8247 sigaddset(&G.blocked_set, sig);
8248 } else {
8249 /* There was a trap handler, we are removing it
8250 * (if sig has non-DFL handling,
8251 * we don't need to do anything) */
8252 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8253 continue;
8254 sigdelset(&G.blocked_set, sig);
8255 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008256 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008257 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008258 return ret;
8259 }
8260
8261 if (!argv[1]) { /* no second arg */
8262 bb_error_msg("trap: invalid arguments");
8263 return EXIT_FAILURE;
8264 }
8265
8266 /* First arg is "-": reset all specified to default */
8267 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8268 /* Everything else: set arg as signal handler
8269 * (includes "" case, which ignores signal) */
8270 if (argv[0][0] == '-') {
8271 if (argv[0][1] == '\0') { /* "-" */
8272 /* new_cmd remains NULL: "reset these sigs" */
8273 goto reset_traps;
8274 }
8275 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8276 argv++;
8277 }
8278 /* else: "-something", no special meaning */
8279 }
8280 new_cmd = *argv;
8281 reset_traps:
8282 argv++;
8283 goto process_sig_list;
8284}
8285
Mike Frysinger93cadc22009-05-27 17:06:25 -04008286/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008287static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008288{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008289 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008290
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008291 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008292 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008293 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008294
8295 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008296 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008297 type = "an alias";*/
8298#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008299 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008300 type = "a function";
8301#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008302 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008303 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008304 else if ((path = find_in_path(*argv)) != NULL)
8305 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008306 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008307 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008308 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008309 continue;
8310 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008311
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008312 printf("%s is %s\n", *argv, type);
8313 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008314 }
8315
8316 return ret;
8317}
8318
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008319#if ENABLE_HUSH_JOB
8320/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008321static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008322{
8323 int i, jobnum;
8324 struct pipe *pi;
8325
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008326 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008327 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008328
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008329 /* If they gave us no args, assume they want the last backgrounded task */
8330 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008331 for (pi = G.job_list; pi; pi = pi->next) {
8332 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008333 goto found;
8334 }
8335 }
8336 bb_error_msg("%s: no current job", argv[0]);
8337 return EXIT_FAILURE;
8338 }
8339 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8340 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8341 return EXIT_FAILURE;
8342 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008343 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008344 if (pi->jobid == jobnum) {
8345 goto found;
8346 }
8347 }
8348 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8349 return EXIT_FAILURE;
8350 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008351 /* TODO: bash prints a string representation
8352 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008353 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008354 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008355 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008356 }
8357
8358 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008359 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8360 for (i = 0; i < pi->num_cmds; i++) {
8361 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8362 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008363 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008364 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008365
8366 i = kill(- pi->pgrp, SIGCONT);
8367 if (i < 0) {
8368 if (errno == ESRCH) {
8369 delete_finished_bg_job(pi);
8370 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008371 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008372 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008373 }
8374
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008375 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008376 remove_bg_job(pi);
8377 return checkjobs_and_fg_shell(pi);
8378 }
8379 return EXIT_SUCCESS;
8380}
8381#endif
8382
8383#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008384static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008385{
8386 const struct built_in_command *x;
8387
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008388 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008389 "Built-in commands:\n"
8390 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008391 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008392 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008393 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008394 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008395 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008396 return EXIT_SUCCESS;
8397}
8398#endif
8399
8400#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008401static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008402{
8403 struct pipe *job;
8404 const char *status_string;
8405
Denis Vlasenko87a86552008-07-29 19:43:10 +00008406 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008407 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008408 status_string = "Stopped";
8409 else
8410 status_string = "Running";
8411
8412 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8413 }
8414 return EXIT_SUCCESS;
8415}
8416#endif
8417
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008418#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008419static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008420{
8421 void *p;
8422 unsigned long l;
8423
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008424# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008425 /* Optional. Reduces probability of false positives */
8426 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008427# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008428 /* Crude attempt to find where "free memory" starts,
8429 * sans fragmentation. */
8430 p = malloc(240);
8431 l = (unsigned long)p;
8432 free(p);
8433 p = malloc(3400);
8434 if (l < (unsigned long)p) l = (unsigned long)p;
8435 free(p);
8436
8437 if (!G.memleak_value)
8438 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008439
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008440 l -= G.memleak_value;
8441 if ((long)l < 0)
8442 l = 0;
8443 l /= 1024;
8444 if (l > 127)
8445 l = 127;
8446
8447 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8448 return l;
8449}
8450#endif
8451
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008452static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008453{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008454 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008455 return EXIT_SUCCESS;
8456}
8457
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008458static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008459{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008460 const char *r;
8461 char *opt_n = NULL;
8462 char *opt_p = NULL;
8463 char *opt_t = NULL;
8464 char *opt_u = NULL;
8465 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008466
Denys Vlasenko03dad222010-01-12 23:29:57 +01008467 /* "!": do not abort on errors.
8468 * Option string must start with "sr" to match BUILTIN_READ_xxx
8469 */
8470 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8471 if (read_flags == (uint32_t)-1)
8472 return EXIT_FAILURE;
8473 argv += optind;
8474
8475 r = shell_builtin_read(set_local_var_from_halves,
8476 argv,
8477 get_local_var_value("IFS"), /* can be NULL */
8478 read_flags,
8479 opt_n,
8480 opt_p,
8481 opt_t,
8482 opt_u
8483 );
8484
8485 if ((uintptr_t)r > 1) {
8486 bb_error_msg("%s", r);
8487 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008488 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008489
Denys Vlasenko03dad222010-01-12 23:29:57 +01008490 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008491}
8492
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008493/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8494 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008495 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008496 * set [-abCefhmnuvx] [-o option] [argument...]
8497 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008498 * set -- [argument...]
8499 * set -o
8500 * set +o
8501 * Implementations shall support the options in both their hyphen and
8502 * plus-sign forms. These options can also be specified as options to sh.
8503 * Examples:
8504 * Write out all variables and their values: set
8505 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8506 * Turn on the -x and -v options: set -xv
8507 * Unset all positional parameters: set --
8508 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8509 * Set the positional parameters to the expansion of x, even if x expands
8510 * with a leading '-' or '+': set -- $x
8511 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008512 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008513 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008514static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008515{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008516 int n;
8517 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008518 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008519
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008520 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008521 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008522 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008523 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008524 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008525 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008526
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008527 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008528 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008529 ++argv;
8530 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008531 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008532 if (arg[0] != '+' && arg[0] != '-')
8533 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008534 for (n = 1; arg[n]; ++n) {
8535 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008536 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008537 if (arg[n] == 'o' && argv[1])
8538 argv++;
8539 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008540 } while ((arg = *++argv) != NULL);
8541 /* Now argv[0] is 1st argument */
8542
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008543 if (arg == NULL)
8544 return EXIT_SUCCESS;
8545 set_argv:
8546
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008547 /* NB: G.global_argv[0] ($0) is never freed/changed */
8548 g_argv = G.global_argv;
8549 if (G.global_args_malloced) {
8550 pp = g_argv;
8551 while (*++pp)
8552 free(*pp);
8553 g_argv[1] = NULL;
8554 } else {
8555 G.global_args_malloced = 1;
8556 pp = xzalloc(sizeof(pp[0]) * 2);
8557 pp[0] = g_argv[0]; /* retain $0 */
8558 g_argv = pp;
8559 }
8560 /* This realloc's G.global_argv */
8561 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8562
8563 n = 1;
8564 while (*++pp)
8565 n++;
8566 G.global_argc = n;
8567
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008568 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008569
8570 /* Nothing known, so abort */
8571 error:
8572 bb_error_msg("set: %s: invalid option", arg);
8573 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008574}
8575
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008576static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008577{
8578 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008579 argv = skip_dash_dash(argv);
8580 if (argv[0]) {
8581 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008582 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008583 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008584 if (G.global_args_malloced) {
8585 int m = 1;
8586 while (m <= n)
8587 free(G.global_argv[m++]);
8588 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008589 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008590 memmove(&G.global_argv[1], &G.global_argv[n+1],
8591 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008592 return EXIT_SUCCESS;
8593 }
8594 return EXIT_FAILURE;
8595}
8596
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008597static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008598{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008599 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008600 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008601 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008602#if ENABLE_HUSH_FUNCTIONS
8603 smallint sv_flg;
8604#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008605
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008606 argv = skip_dash_dash(argv);
8607 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008608 if (!filename) {
8609 /* bash says: "bash: .: filename argument required" */
8610 return 2; /* bash compat */
8611 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008612 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008613 if (!strchr(filename, '/')) {
8614 arg_path = find_in_path(filename);
8615 if (arg_path)
8616 filename = arg_path;
8617 }
8618 input = fopen_or_warn(filename, "r");
8619 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008620 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008621 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008622 return EXIT_FAILURE;
8623 }
8624 close_on_exec_on(fileno(input));
8625
Mike Frysinger885b6f22009-04-18 21:04:25 +00008626#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008627 sv_flg = G.flag_return_in_progress;
8628 /* "we are inside sourced file, ok to use return" */
8629 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008630#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008631 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008632
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01008633//TODO: syntax errors in sourced file should never abort the "calling" script.
8634//Try: bash -c '. ./bad_file; echo YES'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008635 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008636 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008637
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008638 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008639#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008640 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008641#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008642
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008643 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008644}
8645
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008646static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008647{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008648 int rc;
8649 mode_t mask;
8650
8651 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008652 argv = skip_dash_dash(argv);
8653 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008654 mode_t old_mask = mask;
8655
8656 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008657 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008658 mask ^= 0777;
8659 if (rc == 0) {
8660 mask = old_mask;
8661 /* bash messages:
8662 * bash: umask: 'q': invalid symbolic mode operator
8663 * bash: umask: 999: octal number out of range
8664 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008665 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008666 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008667 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008668 rc = 1;
8669 /* Mimic bash */
8670 printf("%04o\n", (unsigned) mask);
8671 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008672 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008673 umask(mask);
8674
8675 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008676}
8677
Mike Frysingerd690f682009-03-30 06:50:54 +00008678/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008679static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008680{
Mike Frysingerd690f682009-03-30 06:50:54 +00008681 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008682 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008683
Denis Vlasenko28e67962009-04-26 23:22:40 +00008684 /* "!": do not abort on errors */
8685 /* "+": stop at 1st non-option */
8686 opts = getopt32(argv, "!+vf");
8687 if (opts == (unsigned)-1)
8688 return EXIT_FAILURE;
8689 if (opts == 3) {
8690 bb_error_msg("unset: -v and -f are exclusive");
8691 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008692 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008693 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008694
8695 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008696 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008697 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008698 if (unset_local_var(*argv)) {
8699 /* unset <nonexistent_var> doesn't fail.
8700 * Error is when one tries to unset RO var.
8701 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008702 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008703 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008704 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008705#if ENABLE_HUSH_FUNCTIONS
8706 else {
8707 unset_func(*argv);
8708 }
8709#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008710 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008711 }
8712 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008713}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008714
Mike Frysinger56bdea12009-03-28 20:01:58 +00008715/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008716static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008717{
8718 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008719 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008720
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008721 argv = skip_dash_dash(argv);
8722 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008723 /* Don't care about wait results */
8724 /* Note 1: must wait until there are no more children */
8725 /* Note 2: must be interruptible */
8726 /* Examples:
8727 * $ sleep 3 & sleep 6 & wait
8728 * [1] 30934 sleep 3
8729 * [2] 30935 sleep 6
8730 * [1] Done sleep 3
8731 * [2] Done sleep 6
8732 * $ sleep 3 & sleep 6 & wait
8733 * [1] 30936 sleep 3
8734 * [2] 30937 sleep 6
8735 * [1] Done sleep 3
8736 * ^C <-- after ~4 sec from keyboard
8737 * $
8738 */
8739 sigaddset(&G.blocked_set, SIGCHLD);
8740 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8741 while (1) {
8742 checkjobs(NULL);
8743 if (errno == ECHILD)
8744 break;
8745 /* Wait for SIGCHLD or any other signal of interest */
8746 /* sigtimedwait with infinite timeout: */
8747 sig = sigwaitinfo(&G.blocked_set, NULL);
8748 if (sig > 0) {
8749 sig = check_and_run_traps(sig);
8750 if (sig && sig != SIGCHLD) { /* see note 2 */
8751 ret = 128 + sig;
8752 break;
8753 }
8754 }
8755 }
8756 sigdelset(&G.blocked_set, SIGCHLD);
8757 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8758 return ret;
8759 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008760
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008761 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008762 while (*argv) {
8763 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008764 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008765 /* mimic bash message */
8766 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008767 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008768 }
8769 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008770 if (WIFSIGNALED(status))
8771 ret = 128 + WTERMSIG(status);
8772 else if (WIFEXITED(status))
8773 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008774 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008775 ret = EXIT_FAILURE;
8776 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008777 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008778 ret = 127;
8779 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008780 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008781 }
8782
8783 return ret;
8784}
8785
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008786#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8787static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8788{
8789 if (argv[1]) {
8790 def = bb_strtou(argv[1], NULL, 10);
8791 if (errno || def < def_min || argv[2]) {
8792 bb_error_msg("%s: bad arguments", argv[0]);
8793 def = UINT_MAX;
8794 }
8795 }
8796 return def;
8797}
8798#endif
8799
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008800#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008801static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008802{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008803 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008804 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008805 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008806 return EXIT_SUCCESS; /* bash compat */
8807 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008808 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008809
8810 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8811 if (depth == UINT_MAX)
8812 G.flag_break_continue = BC_BREAK;
8813 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008814 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008815
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008816 return EXIT_SUCCESS;
8817}
8818
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008819static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008820{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008821 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8822 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008823}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008824#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008825
8826#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008827static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008828{
8829 int rc;
8830
8831 if (G.flag_return_in_progress != -1) {
8832 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8833 return EXIT_FAILURE; /* bash compat */
8834 }
8835
8836 G.flag_return_in_progress = 1;
8837
8838 /* bash:
8839 * out of range: wraps around at 256, does not error out
8840 * non-numeric param:
8841 * f() { false; return qwe; }; f; echo $?
8842 * bash: return: qwe: numeric argument required <== we do this
8843 * 255 <== we also do this
8844 */
8845 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8846 return rc;
8847}
8848#endif