blob: 5b73f0c53e862aea70f8f510c9dbbe7b1058daa4 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
11 * Credits:
12 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000013 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000016 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000017 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
21 * rewrites.
22 *
Eric Andersen25f27032001-04-26 23:22:31 +000023 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000024 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000025 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000026 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000028 *
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
39 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020040 * TODOs:
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
43 * tilde expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000044 * aliases
Denys Vlasenko349ef962010-05-21 15:46:24 +020045 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020048 * make complex ${var%...} constructs support optional
49 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000050 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020051 * Bash compat TODO:
52 * redirection of stdout+stderr: &> and >&
53 * brace expansion: one/{two,three,four}
54 * reserved words: function select
55 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020056 * process substitution: <(list) and >(list)
57 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020058 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020059 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
60 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
61 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020062 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020063 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
64 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko08218012009-06-03 14:43:56 +020066 * export builtin should be special, its arguments are assignments
67 * and therefore expansion of them should be "one-word" expansion:
68 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
69 * compare with:
70 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
71 * ls: cannot access i=a: No such file or directory
72 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020073 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020074 * Note2: bash 3.2.33(1) does this only if export word itself
75 * is not quoted:
76 * $ export i=`echo 'aaa bbb'`; echo "$i"
77 * aaa bbb
78 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
79 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000080 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +020081 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
Eric Andersen25f27032001-04-26 23:22:31 +000082 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020083#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denys Vlasenko27726cb2009-09-12 14:48:33 +020084#include <malloc.h> /* for malloc_trim */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000085#include <glob.h>
86/* #include <dmalloc.h> */
87#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000088# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000089#endif
Denys Vlasenko03dad222010-01-12 23:29:57 +010090
91#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000092#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000093#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +020094#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +020095# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +020096#else
97# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +020098#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000099#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200100# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000101#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000102
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
104//applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
106//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
107
108//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
109//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
110
111//config:config HUSH
112//config: bool "hush"
113//config: default y
114//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200115//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200116//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
117//config: case/esac. Redirections, here documents, $((arithmetic))
118//config: and functions are supported.
119//config:
120//config: It will compile and work on no-mmu systems.
121//config:
122//config: It does not handle select, aliases, brace expansion,
123//config: tilde expansion, &>file and >&file redirection of stdout+stderr.
124//config:
125//config:config HUSH_BASH_COMPAT
126//config: bool "bash-compatible extensions"
127//config: default y
128//config: depends on HUSH
129//config: help
130//config: Enable bash-compatible extensions.
131//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200132//config:config HUSH_BRACE_EXPANSION
133//config: bool "Brace expansion"
134//config: default y
135//config: depends on HUSH_BASH_COMPAT
136//config: help
137//config: Enable {abc,def} extension.
138//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200139//config:config HUSH_HELP
140//config: bool "help builtin"
141//config: default y
142//config: depends on HUSH
143//config: help
144//config: Enable help builtin in hush. Code size + ~1 kbyte.
145//config:
146//config:config HUSH_INTERACTIVE
147//config: bool "Interactive mode"
148//config: default y
149//config: depends on HUSH
150//config: help
151//config: Enable interactive mode (prompt and command editing).
152//config: Without this, hush simply reads and executes commands
153//config: from stdin just like a shell script from a file.
154//config: No prompt, no PS1/PS2 magic shell variables.
155//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200156//config:config HUSH_SAVEHISTORY
157//config: bool "Save command history to .hush_history"
158//config: default y
159//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
160//config: help
161//config: Enable history saving in hush.
162//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config:config HUSH_JOB
164//config: bool "Job control"
165//config: default y
166//config: depends on HUSH_INTERACTIVE
167//config: help
168//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
169//config: command (not entire shell), fg/bg builtins work. Without this option,
170//config: "cmd &" still works by simply spawning a process and immediately
171//config: prompting for next command (or executing next command in a script),
172//config: but no separate process group is formed.
173//config:
174//config:config HUSH_TICK
175//config: bool "Process substitution"
176//config: default y
177//config: depends on HUSH
178//config: help
179//config: Enable process substitution `command` and $(command) in hush.
180//config:
181//config:config HUSH_IF
182//config: bool "Support if/then/elif/else/fi"
183//config: default y
184//config: depends on HUSH
185//config: help
186//config: Enable if/then/elif/else/fi in hush.
187//config:
188//config:config HUSH_LOOPS
189//config: bool "Support for, while and until loops"
190//config: default y
191//config: depends on HUSH
192//config: help
193//config: Enable for, while and until loops in hush.
194//config:
195//config:config HUSH_CASE
196//config: bool "Support case ... esac statement"
197//config: default y
198//config: depends on HUSH
199//config: help
200//config: Enable case ... esac statement in hush. +400 bytes.
201//config:
202//config:config HUSH_FUNCTIONS
203//config: bool "Support funcname() { commands; } syntax"
204//config: default y
205//config: depends on HUSH
206//config: help
207//config: Enable support for shell functions in hush. +800 bytes.
208//config:
209//config:config HUSH_LOCAL
210//config: bool "Support local builtin"
211//config: default y
212//config: depends on HUSH_FUNCTIONS
213//config: help
214//config: Enable support for local variables in functions.
215//config:
216//config:config HUSH_RANDOM_SUPPORT
217//config: bool "Pseudorandom generator and $RANDOM variable"
218//config: default y
219//config: depends on HUSH
220//config: help
221//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
222//config: Each read of "$RANDOM" will generate a new pseudorandom value.
223//config:
224//config:config HUSH_EXPORT_N
225//config: bool "Support 'export -n' option"
226//config: default y
227//config: depends on HUSH
228//config: help
229//config: export -n unexports variables. It is a bash extension.
230//config:
231//config:config HUSH_MODE_X
232//config: bool "Support 'hush -x' option and 'set -x' command"
233//config: default y
234//config: depends on HUSH
235//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200236//config: This instructs hush to print commands before execution.
237//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200238//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200239//config:config MSH
240//config: bool "msh (deprecated: aliased to hush)"
241//config: default n
242//config: select HUSH
243//config: help
244//config: msh is deprecated and will be removed, please migrate to hush.
245//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200246
247//usage:#define hush_trivial_usage NOUSAGE_STR
248//usage:#define hush_full_usage ""
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200249//usage:#define msh_trivial_usage NOUSAGE_STR
250//usage:#define msh_full_usage ""
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +0200251//usage:#define sh_trivial_usage NOUSAGE_STR
252//usage:#define sh_full_usage ""
253//usage:#define bash_trivial_usage NOUSAGE_STR
254//usage:#define bash_full_usage ""
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200255
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000256
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200257/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000258#define LEAK_HUNTING 0
259#define BUILD_AS_NOMMU 0
260/* Enable/disable sanity checks. Ok to enable in production,
261 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
262 * Keeping 1 for now even in released versions.
263 */
264#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200265/* Slightly bigger (+200 bytes), but faster hush.
266 * So far it only enables a trick with counting SIGCHLDs and forks,
267 * which allows us to do fewer waitpid's.
268 * (we can detect a case where neither forks were done nor SIGCHLDs happened
269 * and therefore waitpid will return the same result as last time)
270 */
271#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200272/* TODO: implement simplified code for users which do not need ${var%...} ops
273 * So far ${var%...} ops are always enabled:
274 */
275#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000276
277
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000278#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000279# undef BB_MMU
280# undef USE_FOR_NOMMU
281# undef USE_FOR_MMU
282# define BB_MMU 0
283# define USE_FOR_NOMMU(...) __VA_ARGS__
284# define USE_FOR_MMU(...)
285#endif
286
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200287#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100288#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000289/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000290# undef CONFIG_FEATURE_SH_STANDALONE
291# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000292# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100293# undef IF_NOT_FEATURE_SH_STANDALONE
294# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000295# define IF_FEATURE_SH_STANDALONE(...)
296# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000297#endif
298
Denis Vlasenko05743d72008-02-10 12:10:08 +0000299#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000300# undef ENABLE_FEATURE_EDITING
301# define ENABLE_FEATURE_EDITING 0
302# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
303# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000304#endif
305
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000306/* Do we support ANY keywords? */
307#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000308# define HAS_KEYWORDS 1
309# define IF_HAS_KEYWORDS(...) __VA_ARGS__
310# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000311#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000312# define HAS_KEYWORDS 0
313# define IF_HAS_KEYWORDS(...)
314# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000315#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000316
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000317/* If you comment out one of these below, it will be #defined later
318 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000319#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000320/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000321#define debug_printf_parse(...) do {} while (0)
322#define debug_print_tree(a, b) do {} while (0)
323#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000324#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000325#define debug_printf_jobs(...) do {} while (0)
326#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200327#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000328#define debug_printf_glob(...) do {} while (0)
329#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000330#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000331#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000332
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000333#define ERR_PTR ((void*)(long)1)
334
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200335#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000336
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200337#define _SPECIAL_VARS_STR "_*@$!?#"
338#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
339#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200340#if ENABLE_HUSH_BASH_COMPAT
341/* Support / and // replace ops */
342/* Note that // is stored as \ in "encoded" string representation */
343# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
344# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
345# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
346#else
347# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
348# define VAR_SUBST_OPS "%#:-=+?"
349# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
350#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200351
352#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000353
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200354struct variable;
355
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000356static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
357
358/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000359 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000360 */
361#if !BB_MMU
362typedef struct nommu_save_t {
363 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200364 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000365 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000366 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000367} nommu_save_t;
368#endif
369
Denys Vlasenko9b782552010-09-08 13:33:26 +0200370enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000371 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000372#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000373 RES_IF ,
374 RES_THEN ,
375 RES_ELIF ,
376 RES_ELSE ,
377 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000378#endif
379#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000380 RES_FOR ,
381 RES_WHILE ,
382 RES_UNTIL ,
383 RES_DO ,
384 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000385#endif
386#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000387 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000388#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000389#if ENABLE_HUSH_CASE
390 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200391 /* three pseudo-keywords support contrived "case" syntax: */
392 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
393 RES_MATCH , /* "word)" */
394 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000395 RES_ESAC ,
396#endif
397 RES_XXXX ,
398 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200399};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000400
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000401typedef struct o_string {
402 char *data;
403 int length; /* position where data is appended */
404 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200405 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000406 /* At least some part of the string was inside '' or "",
407 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200408 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000409 smallint has_empty_slot;
410 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
411} o_string;
412enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200413 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
414 EXP_FLAG_GLOB = 0x2,
415 /* Protect newly added chars against globbing
416 * by prepending \ to *, ?, [, \ */
417 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
418};
419enum {
420 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000421 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200422 NOT_ASSIGNMENT = 2,
423 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
424 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000425};
426/* Used for initialization: o_string foo = NULL_O_STRING; */
427#define NULL_O_STRING { NULL }
428
429/* I can almost use ordinary FILE*. Is open_memstream() universally
430 * available? Where is it documented? */
431typedef struct in_str {
432 const char *p;
433 /* eof_flag=1: last char in ->p is really an EOF */
434 char eof_flag; /* meaningless if ->p == NULL */
435 char peek_buf[2];
436#if ENABLE_HUSH_INTERACTIVE
437 smallint promptme;
438 smallint promptmode; /* 0: PS1, 1: PS2 */
439#endif
440 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200441 int (*get) (struct in_str *) FAST_FUNC;
442 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000443} in_str;
444#define i_getch(input) ((input)->get(input))
445#define i_peek(input) ((input)->peek(input))
446
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200447/* The descrip member of this structure is only used to make
448 * debugging output pretty */
449static const struct {
450 int mode;
451 signed char default_fd;
452 char descrip[3];
453} redir_table[] = {
454 { O_RDONLY, 0, "<" },
455 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
456 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
457 { O_CREAT|O_RDWR, 1, "<>" },
458 { O_RDONLY, 0, "<<" },
459/* Should not be needed. Bogus default_fd helps in debugging */
460/* { O_RDONLY, 77, "<<" }, */
461};
462
Eric Andersen25f27032001-04-26 23:22:31 +0000463struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000464 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000465 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000466 int rd_fd; /* fd to redirect */
467 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
468 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000469 smallint rd_type; /* (enum redir_type) */
470 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000471 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200472 * bit 0: do we need to trim leading tabs?
473 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000474 */
Eric Andersen25f27032001-04-26 23:22:31 +0000475};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000476typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200477 REDIRECT_INPUT = 0,
478 REDIRECT_OVERWRITE = 1,
479 REDIRECT_APPEND = 2,
480 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000481 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200482 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000483
484 REDIRFD_CLOSE = -3,
485 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000486 REDIRFD_TO_FILE = -1,
487 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000488
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000489 HEREDOC_SKIPTABS = 1,
490 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000491} redir_type;
492
Eric Andersen25f27032001-04-26 23:22:31 +0000493
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000494struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000495 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000496 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000497 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200498 smallint cmd_type; /* CMD_xxx */
499#define CMD_NORMAL 0
500#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200501#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200502/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200503# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000504#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200505#if ENABLE_HUSH_FUNCTIONS
506# define CMD_FUNCDEF 3
507#endif
508
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200509 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
510 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000511#if !BB_MMU
512 char *group_as_string;
513#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000514#if ENABLE_HUSH_FUNCTIONS
515 struct function *child_func;
516/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200517 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000518 * When we execute "f1() {a;}" cmd, we create new function and clear
519 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200520 * When we execute "f1() {b;}", we notice that f1 exists,
521 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000522 * we put those fields back into cmd->xxx
523 * (struct function has ->parent_cmd ptr to facilitate that).
524 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
525 * Without this trick, loop would execute a;b;b;b;...
526 * instead of correct sequence a;b;a;b;...
527 * When command is freed, it severs the link
528 * (sets ->child_func->parent_cmd to NULL).
529 */
530#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000531 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000532/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
533 * and on execution these are substituted with their values.
534 * Substitution can make _several_ words out of one argv[n]!
535 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000536 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000537 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000538 struct redir_struct *redirects; /* I/O redirections */
539};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000540/* Is there anything in this command at all? */
541#define IS_NULL_CMD(cmd) \
542 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
543
Eric Andersen25f27032001-04-26 23:22:31 +0000544
545struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000546 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000547 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000548 int alive_cmds; /* number of commands running (not exited) */
549 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000550#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000551 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000552 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000553 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000554#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000555 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000556 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000557 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
558 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000559};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000560typedef enum pipe_style {
561 PIPE_SEQ = 1,
562 PIPE_AND = 2,
563 PIPE_OR = 3,
564 PIPE_BG = 4,
565} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000566/* Is there anything in this pipe at all? */
567#define IS_NULL_PIPE(pi) \
568 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000569
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000570/* This holds pointers to the various results of parsing */
571struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000572 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000573 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000574 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000575 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000576 /* last command in pipe (being constructed right now) */
577 struct command *command;
578 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000579 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000580#if !BB_MMU
581 o_string as_string;
582#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000583#if HAS_KEYWORDS
584 smallint ctx_res_w;
585 smallint ctx_inverted; /* "! cmd | cmd" */
586#if ENABLE_HUSH_CASE
587 smallint ctx_dsemicolon; /* ";;" seen */
588#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000589 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
590 int old_flag;
591 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000592 * example: "if pipe1; pipe2; then pipe3; fi"
593 * when we see "if" or "then", we malloc and copy current context,
594 * and make ->stack point to it. then we parse pipeN.
595 * when closing "then" / fi" / whatever is found,
596 * we move list_head into ->stack->command->group,
597 * copy ->stack into current context, and delete ->stack.
598 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000599 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000600 struct parse_context *stack;
601#endif
602};
603
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000604/* On program start, environ points to initial environment.
605 * putenv adds new pointers into it, unsetenv removes them.
606 * Neither of these (de)allocates the strings.
607 * setenv allocates new strings in malloc space and does putenv,
608 * and thus setenv is unusable (leaky) for shell's purposes */
609#define setenv(...) setenv_is_leaky_dont_use()
610struct variable {
611 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000612 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200613#if ENABLE_HUSH_LOCAL
614 unsigned func_nest_level;
615#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000616 int max_len; /* if > 0, name is part of initial env; else name is malloced */
617 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000618 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000619};
620
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000621enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000622 BC_BREAK = 1,
623 BC_CONTINUE = 2,
624};
625
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000626#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000627struct function {
628 struct function *next;
629 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000630 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000631 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200632# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000633 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200634# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000635};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000636#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000637
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000638
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000639/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000640/* Sorted roughly by size (smaller offsets == smaller code) */
641struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000642 /* interactive_fd != 0 means we are an interactive shell.
643 * If we are, then saved_tty_pgrp can also be != 0, meaning
644 * that controlling tty is available. With saved_tty_pgrp == 0,
645 * job control still works, but terminal signals
646 * (^C, ^Z, ^Y, ^\) won't work at all, and background
647 * process groups can only be created with "cmd &".
648 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
649 * to give tty to the foreground process group,
650 * and will take it back when the group is stopped (^Z)
651 * or killed (^C).
652 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000653#if ENABLE_HUSH_INTERACTIVE
654 /* 'interactive_fd' is a fd# open to ctty, if we have one
655 * _AND_ if we decided to act interactively */
656 int interactive_fd;
657 const char *PS1;
658 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000659# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000660#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000661# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000662#endif
663#if ENABLE_FEATURE_EDITING
664 line_input_t *line_input_state;
665#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000666 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200667 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000668 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200669#if ENABLE_HUSH_RANDOM_SUPPORT
670 random_t random_gen;
671#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000672#if ENABLE_HUSH_JOB
673 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000674 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000675 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000676 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400677# define G_saved_tty_pgrp (G.saved_tty_pgrp)
678#else
679# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000680#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000681 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000682#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000683 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000684#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000685#if ENABLE_HUSH_FUNCTIONS
686 /* 0: outside of a function (or sourced file)
687 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000688 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000689 */
690 smallint flag_return_in_progress;
691#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200692 smallint n_mode;
693#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200694 smallint x_mode;
Denys Vlasenko29082232010-07-16 13:52:32 +0200695# define G_x_mode (G.x_mode)
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200696#else
697# define G_x_mode 0
698#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000699 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000700 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000701 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000702 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000703 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100704 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000705 /* how many non-NULL argv's we have. NB: $# + 1 */
706 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000707 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000708#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000709 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000710#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000711#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000712 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000713 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000714#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000715 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000716 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200717 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200718 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000719#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000720 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200721# if ENABLE_HUSH_LOCAL
722 struct variable **shadowed_vars_pp;
723 unsigned func_nest_level;
724# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000725#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000726 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200727#if ENABLE_HUSH_FAST
728 unsigned count_SIGCHLD;
729 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200730 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200731#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000732 /* which signals have non-DFL handler (even with no traps set)? */
733 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000734 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000735 sigset_t blocked_set;
736 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000737#if HUSH_DEBUG
738 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000739 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000740#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200741 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000742};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000743#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000744/* Not #defining name to G.name - this quickly gets unwieldy
745 * (too many defines). Also, I actually prefer to see when a variable
746 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000747#define INIT_G() do { \
748 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
749} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000750
751
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000752/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200753static int builtin_cd(char **argv) FAST_FUNC;
754static int builtin_echo(char **argv) FAST_FUNC;
755static int builtin_eval(char **argv) FAST_FUNC;
756static int builtin_exec(char **argv) FAST_FUNC;
757static int builtin_exit(char **argv) FAST_FUNC;
758static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000759#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200760static int builtin_fg_bg(char **argv) FAST_FUNC;
761static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000762#endif
763#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200764static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000765#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200766#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200767static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200768#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000769#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200770static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000771#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400772#if ENABLE_PRINTF
773static int builtin_printf(char **argv) FAST_FUNC;
774#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200775static int builtin_pwd(char **argv) FAST_FUNC;
776static int builtin_read(char **argv) FAST_FUNC;
777static int builtin_set(char **argv) FAST_FUNC;
778static int builtin_shift(char **argv) FAST_FUNC;
779static int builtin_source(char **argv) FAST_FUNC;
780static int builtin_test(char **argv) FAST_FUNC;
781static int builtin_trap(char **argv) FAST_FUNC;
782static int builtin_type(char **argv) FAST_FUNC;
783static int builtin_true(char **argv) FAST_FUNC;
784static int builtin_umask(char **argv) FAST_FUNC;
785static int builtin_unset(char **argv) FAST_FUNC;
786static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000787#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200788static int builtin_break(char **argv) FAST_FUNC;
789static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000790#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000791#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200792static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000793#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000794
795/* Table of built-in functions. They can be forked or not, depending on
796 * context: within pipes, they fork. As simple commands, they do not.
797 * When used in non-forking context, they can change global variables
798 * in the parent shell process. If forked, of course they cannot.
799 * For example, 'unset foo | whatever' will parse and run, but foo will
800 * still be set at the end. */
801struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100802 const char *b_cmd;
803 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000804#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100805 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200806# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000807#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200808# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000809#endif
810};
811
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200812static const struct built_in_command bltins1[] = {
813 BLTIN("." , builtin_source , "Run commands in a file"),
814 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000815#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200816 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000817#endif
818#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200819 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000820#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200821 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000822#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200823 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000824#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200825 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
826 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
827 BLTIN("exit" , builtin_exit , "Exit"),
828 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000829#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200830 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000831#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000832#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200833 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000834#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000835#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200836 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000837#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200838#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200839 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200840#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000841#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200842 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000843#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200844 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000845#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200846 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000847#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200848 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
849 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200850#if ENABLE_HUSH_BASH_COMPAT
851 BLTIN("source" , builtin_source , "Run commands in a file"),
852#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200853 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100854 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100855 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200856 BLTIN("umask" , builtin_umask , "Set file creation mask"),
857 BLTIN("unset" , builtin_unset , "Unset variables"),
858 BLTIN("wait" , builtin_wait , "Wait for process"),
859};
860/* For now, echo and test are unconditionally enabled.
861 * Maybe make it configurable? */
862static const struct built_in_command bltins2[] = {
863 BLTIN("[" , builtin_test , NULL),
864 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400865#if ENABLE_PRINTF
866 BLTIN("printf" , builtin_printf , NULL),
867#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200868 BLTIN("pwd" , builtin_pwd , NULL),
869 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000870};
871
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000872
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000873/* Debug printouts.
874 */
875#if HUSH_DEBUG
876/* prevent disasters with G.debug_indent < 0 */
877# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
878# define debug_enter() (G.debug_indent++)
879# define debug_leave() (G.debug_indent--)
880#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200881# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000882# define debug_enter() ((void)0)
883# define debug_leave() ((void)0)
884#endif
885
886#ifndef debug_printf
887# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
888#endif
889
890#ifndef debug_printf_parse
891# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
892#endif
893
894#ifndef debug_printf_exec
895#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
896#endif
897
898#ifndef debug_printf_env
899# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
900#endif
901
902#ifndef debug_printf_jobs
903# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
904# define DEBUG_JOBS 1
905#else
906# define DEBUG_JOBS 0
907#endif
908
909#ifndef debug_printf_expand
910# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
911# define DEBUG_EXPAND 1
912#else
913# define DEBUG_EXPAND 0
914#endif
915
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200916#ifndef debug_printf_varexp
917# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
918#endif
919
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000920#ifndef debug_printf_glob
921# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
922# define DEBUG_GLOB 1
923#else
924# define DEBUG_GLOB 0
925#endif
926
927#ifndef debug_printf_list
928# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
929#endif
930
931#ifndef debug_printf_subst
932# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
933#endif
934
935#ifndef debug_printf_clean
936# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
937# define DEBUG_CLEAN 1
938#else
939# define DEBUG_CLEAN 0
940#endif
941
942#if DEBUG_EXPAND
943static void debug_print_strings(const char *prefix, char **vv)
944{
945 indent();
946 fprintf(stderr, "%s:\n", prefix);
947 while (*vv)
948 fprintf(stderr, " '%s'\n", *vv++);
949}
950#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200951# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000952#endif
953
954
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000955/* Leak hunting. Use hush_leaktool.sh for post-processing.
956 */
957#if LEAK_HUNTING
958static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000959{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000960 void *ptr = xmalloc((size + 0xff) & ~0xff);
961 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
962 return ptr;
963}
964static void *xxrealloc(int lineno, void *ptr, size_t size)
965{
966 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
967 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
968 return ptr;
969}
970static char *xxstrdup(int lineno, const char *str)
971{
972 char *ptr = xstrdup(str);
973 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
974 return ptr;
975}
976static void xxfree(void *ptr)
977{
978 fdprintf(2, "free %p\n", ptr);
979 free(ptr);
980}
Denys Vlasenko8391c482010-05-22 17:50:43 +0200981# define xmalloc(s) xxmalloc(__LINE__, s)
982# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
983# define xstrdup(s) xxstrdup(__LINE__, s)
984# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000985#endif
986
987
988/* Syntax and runtime errors. They always abort scripts.
989 * In interactive use they usually discard unparsed and/or unexecuted commands
990 * and return to the prompt.
991 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
992 */
993#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200994# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000995# define syntax_error(lineno, msg) syntax_error(msg)
996# define syntax_error_at(lineno, msg) syntax_error_at(msg)
997# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
998# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
999# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001000#endif
1001
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001002static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001003{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001004 va_list p;
1005
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001006#if HUSH_DEBUG >= 2
1007 bb_error_msg("hush.c:%u", lineno);
1008#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001009 va_start(p, fmt);
1010 bb_verror_msg(fmt, p, NULL);
1011 va_end(p);
1012 if (!G_interactive_fd)
1013 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001014}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001015
1016static void syntax_error(unsigned lineno, const char *msg)
1017{
1018 if (msg)
1019 die_if_script(lineno, "syntax error: %s", msg);
1020 else
1021 die_if_script(lineno, "syntax error", NULL);
1022}
1023
1024static void syntax_error_at(unsigned lineno, const char *msg)
1025{
1026 die_if_script(lineno, "syntax error at '%s'", msg);
1027}
1028
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001029static void syntax_error_unterm_str(unsigned lineno, const char *s)
1030{
1031 die_if_script(lineno, "syntax error: unterminated %s", s);
1032}
1033
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001034/* It so happens that all such cases are totally fatal
1035 * even if shell is interactive: EOF while looking for closing
1036 * delimiter. There is nowhere to read stuff from after that,
1037 * it's EOF! The only choice is to terminate.
1038 */
1039static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001040static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001041{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001042 char msg[2] = { ch, '\0' };
1043 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001044 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001045}
1046
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001047static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001048{
1049 char msg[2];
1050 msg[0] = ch;
1051 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001052 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001053}
1054
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001055#if HUSH_DEBUG < 2
1056# undef die_if_script
1057# undef syntax_error
1058# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001059# undef syntax_error_unterm_ch
1060# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001061# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001062#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001063# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001064# define syntax_error(msg) syntax_error(__LINE__, msg)
1065# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1066# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1067# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1068# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001069#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001070
Denis Vlasenko552433b2009-04-04 19:29:21 +00001071
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001072#if ENABLE_HUSH_INTERACTIVE
1073static void cmdedit_update_prompt(void);
1074#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001075# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001076#endif
1077
1078
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001079/* Utility functions
1080 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001081/* Replace each \x with x in place, return ptr past NUL. */
1082static char *unbackslash(char *src)
1083{
Denys Vlasenko71885402009-09-24 01:44:13 +02001084 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001085 while (1) {
1086 if (*src == '\\')
1087 src++;
1088 if ((*dst++ = *src++) == '\0')
1089 break;
1090 }
1091 return dst;
1092}
1093
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001094static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001095{
1096 int i;
1097 unsigned count1;
1098 unsigned count2;
1099 char **v;
1100
1101 v = strings;
1102 count1 = 0;
1103 if (v) {
1104 while (*v) {
1105 count1++;
1106 v++;
1107 }
1108 }
1109 count2 = 0;
1110 v = add;
1111 while (*v) {
1112 count2++;
1113 v++;
1114 }
1115 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1116 v[count1 + count2] = NULL;
1117 i = count2;
1118 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001119 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001120 return v;
1121}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001122#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001123static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1124{
1125 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1126 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1127 return ptr;
1128}
1129#define add_strings_to_strings(strings, add, need_to_dup) \
1130 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1131#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001132
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001133/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001134static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001135{
1136 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001137 v[0] = add;
1138 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001139 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001140}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001141#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001142static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1143{
1144 char **ptr = add_string_to_strings(strings, add);
1145 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1146 return ptr;
1147}
1148#define add_string_to_strings(strings, add) \
1149 xx_add_string_to_strings(__LINE__, strings, add)
1150#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001151
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001152static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001153{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001154 char **v;
1155
1156 if (!strings)
1157 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001158 v = strings;
1159 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001160 free(*v);
1161 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001162 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001163 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001164}
1165
Denis Vlasenko76d50412008-06-10 16:19:39 +00001166
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001167/* Helpers for setting new $n and restoring them back
1168 */
1169typedef struct save_arg_t {
1170 char *sv_argv0;
1171 char **sv_g_argv;
1172 int sv_g_argc;
1173 smallint sv_g_malloced;
1174} save_arg_t;
1175
1176static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1177{
1178 int n;
1179
1180 sv->sv_argv0 = argv[0];
1181 sv->sv_g_argv = G.global_argv;
1182 sv->sv_g_argc = G.global_argc;
1183 sv->sv_g_malloced = G.global_args_malloced;
1184
1185 argv[0] = G.global_argv[0]; /* retain $0 */
1186 G.global_argv = argv;
1187 G.global_args_malloced = 0;
1188
1189 n = 1;
1190 while (*++argv)
1191 n++;
1192 G.global_argc = n;
1193}
1194
1195static void restore_G_args(save_arg_t *sv, char **argv)
1196{
1197 char **pp;
1198
1199 if (G.global_args_malloced) {
1200 /* someone ran "set -- arg1 arg2 ...", undo */
1201 pp = G.global_argv;
1202 while (*++pp) /* note: does not free $0 */
1203 free(*pp);
1204 free(G.global_argv);
1205 }
1206 argv[0] = sv->sv_argv0;
1207 G.global_argv = sv->sv_g_argv;
1208 G.global_argc = sv->sv_g_argc;
1209 G.global_args_malloced = sv->sv_g_malloced;
1210}
1211
1212
Denis Vlasenkod5762932009-03-31 11:22:57 +00001213/* Basic theory of signal handling in shell
1214 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001215 * This does not describe what hush does, rather, it is current understanding
1216 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001217 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1218 *
1219 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1220 * is finished or backgrounded. It is the same in interactive and
1221 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001222 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001223 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001224 * backgrounds (i.e. stops) or kills all members of currently running
1225 * pipe.
1226 *
1227 * Wait builtin in interruptible by signals for which user trap is set
1228 * or by SIGINT in interactive shell.
1229 *
1230 * Trap handlers will execute even within trap handlers. (right?)
1231 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001232 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1233 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001234 *
1235 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001236 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001237 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001238 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001239 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001240 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001241 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001242 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001243 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001244 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001245 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001246 *
1247 * SIGQUIT: ignore
1248 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001249 * SIGHUP (interactive):
1250 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001251 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001252 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1253 * that all pipe members are stopped. Try this in bash:
1254 * while :; do :; done - ^Z does not background it
1255 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001256 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001257 * of the command line, show prompt. NB: ^C does not send SIGINT
1258 * to interactive shell while shell is waiting for a pipe,
1259 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001260 * Example 1: this waits 5 sec, but does not execute ls:
1261 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1262 * Example 2: this does not wait and does not execute ls:
1263 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1264 * Example 3: this does not wait 5 sec, but executes ls:
1265 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001266 *
1267 * (What happens to signals which are IGN on shell start?)
1268 * (What happens with signal mask on shell start?)
1269 *
1270 * Implementation in hush
1271 * ======================
1272 * We use in-kernel pending signal mask to determine which signals were sent.
1273 * We block all signals which we don't want to take action immediately,
1274 * i.e. we block all signals which need to have special handling as described
1275 * above, and all signals which have traps set.
1276 * After each pipe execution, we extract any pending signals via sigtimedwait()
1277 * and act on them.
1278 *
1279 * unsigned non_DFL_mask: a mask of such "special" signals
1280 * sigset_t blocked_set: current blocked signal set
1281 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001282 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001283 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001284 * "trap 'cmd' SIGxxx":
1285 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001286 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001287 * unblock signals with special interactive handling
1288 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001289 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001290 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001291 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001292 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001293 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001294 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001295 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001296 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001297 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001298 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001299 * Standard says "When a subshell is entered, traps that are not being ignored
1300 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001301 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001302 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001303enum {
1304 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001305 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001306 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001307 | (1 << SIGHUP)
1308 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001309 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001310#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001311 | (1 << SIGTTIN)
1312 | (1 << SIGTTOU)
1313 | (1 << SIGTSTP)
1314#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001315};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001316
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001317#if ENABLE_HUSH_FAST
1318static void SIGCHLD_handler(int sig UNUSED_PARAM)
1319{
1320 G.count_SIGCHLD++;
1321//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1322}
1323#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001324
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001325#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001326
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001327/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001328# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001329/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001330# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001331
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001332/* Restores tty foreground process group, and exits.
1333 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001334 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001335 * or called directly with -EXITCODE.
1336 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001337static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001338static void sigexit(int sig)
1339{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001340 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001341 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001342
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001343 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001344 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001345 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1346 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001347
1348 /* Not a signal, just exit */
1349 if (sig <= 0)
1350 _exit(- sig);
1351
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001352 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001353}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001354#else
1355
Denys Vlasenko8391c482010-05-22 17:50:43 +02001356# define disable_restore_tty_pgrp_on_exit() ((void)0)
1357# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001358
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001359#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001360
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001361/* Restores tty foreground process group, and exits. */
1362static void hush_exit(int exitcode) NORETURN;
1363static void hush_exit(int exitcode)
1364{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001365 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1366 /* Prevent recursion:
1367 * trap "echo Hi; exit" EXIT; exit
1368 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001369 char *argv[3];
1370 /* argv[0] is unused */
1371 argv[1] = G.traps[0];
1372 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001373 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001374 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001375 * "trap" will still show it, if executed
1376 * in the handler */
1377 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001378 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001379
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001380#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001381 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001382 sigexit(- (exitcode & 0xff));
1383#else
1384 exit(exitcode);
1385#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001386}
1387
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001388
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001389static int check_and_run_traps(int sig)
1390{
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001391 /* I want it in rodata, not in bss.
1392 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1393 * initializer. But other compilers may still use bss.
1394 * TODO: find more portable solution.
1395 */
1396 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001397 smalluint save_rcode;
1398 int last_sig = 0;
1399
1400 if (sig)
1401 goto jump_in;
1402 while (1) {
1403 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1404 if (sig <= 0)
1405 break;
1406 jump_in:
1407 last_sig = sig;
1408 if (G.traps && G.traps[sig]) {
1409 if (G.traps[sig][0]) {
1410 /* We have user-defined handler */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001411 char *argv[3];
1412 /* argv[0] is unused */
1413 argv[1] = G.traps[sig];
1414 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001415 save_rcode = G.last_exitcode;
1416 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001417 G.last_exitcode = save_rcode;
1418 } /* else: "" trap, ignoring signal */
1419 continue;
1420 }
1421 /* not a trap: special action */
1422 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001423#if ENABLE_HUSH_FAST
1424 case SIGCHLD:
1425 G.count_SIGCHLD++;
1426//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1427 break;
1428#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001429 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001430 /* Builtin was ^C'ed, make it look prettier: */
1431 bb_putchar('\n');
1432 G.flag_SIGINT = 1;
1433 break;
1434#if ENABLE_HUSH_JOB
1435 case SIGHUP: {
1436 struct pipe *job;
1437 /* bash is observed to signal whole process groups,
1438 * not individual processes */
1439 for (job = G.job_list; job; job = job->next) {
1440 if (job->pgrp <= 0)
1441 continue;
1442 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1443 if (kill(- job->pgrp, SIGHUP) == 0)
1444 kill(- job->pgrp, SIGCONT);
1445 }
1446 sigexit(SIGHUP);
1447 }
1448#endif
1449 default: /* ignored: */
1450 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1451 break;
1452 }
1453 }
1454 return last_sig;
1455}
1456
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001457
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001458static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001459{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001460 if (force || G.cwd == NULL) {
1461 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1462 * we must not try to free(bb_msg_unknown) */
1463 if (G.cwd == bb_msg_unknown)
1464 G.cwd = NULL;
1465 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1466 if (!G.cwd)
1467 G.cwd = bb_msg_unknown;
1468 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001469 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001470}
1471
Denis Vlasenko83506862007-11-23 13:11:42 +00001472
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001473/*
1474 * Shell and environment variable support
1475 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001476static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001477{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001478 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001479 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001480
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001481 pp = &G.top_var;
1482 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001483 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001484 return pp;
1485 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001486 }
1487 return NULL;
1488}
1489
Denys Vlasenko03dad222010-01-12 23:29:57 +01001490static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001491{
Denys Vlasenko29082232010-07-16 13:52:32 +02001492 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001493 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001494
1495 if (G.expanded_assignments) {
1496 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001497 while (*cpp) {
1498 char *cp = *cpp;
1499 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1500 return cp + len + 1;
1501 cpp++;
1502 }
1503 }
1504
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001505 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001506 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001507 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001508
Denys Vlasenkodea47882009-10-09 15:40:49 +02001509 if (strcmp(name, "PPID") == 0)
1510 return utoa(G.root_ppid);
1511 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001512#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001513 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001514 return utoa(next_random(&G.random_gen));
1515#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001516 return NULL;
1517}
1518
1519/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001520 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001521 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001522 * 0: do not change export flag
1523 * (if creating new variable, flag will be 0)
1524 * 1: set export flag and putenv the variable
1525 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001526 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001527 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001528#if !BB_MMU && ENABLE_HUSH_LOCAL
1529/* all params are used */
1530#elif BB_MMU && ENABLE_HUSH_LOCAL
1531#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1532 set_local_var(str, flg_export, local_lvl)
1533#elif BB_MMU && !ENABLE_HUSH_LOCAL
1534#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001535 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001536#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1537#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1538 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001539#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001540static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001541{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001542 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001543 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001544 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001545 int name_len;
1546
Denis Vlasenko950bd722009-04-21 11:23:56 +00001547 eq_sign = strchr(str, '=');
1548 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001549 free(str);
1550 return -1;
1551 }
1552
Denis Vlasenko950bd722009-04-21 11:23:56 +00001553 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001554 var_pp = &G.top_var;
1555 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001556 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001557 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001558 continue;
1559 }
1560 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001561 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001562#if !BB_MMU
1563 if (!flg_read_only)
1564#endif
1565 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001566 free(str);
1567 return -1;
1568 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001569 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001570 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1571 *eq_sign = '\0';
1572 unsetenv(str);
1573 *eq_sign = '=';
1574 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001575#if ENABLE_HUSH_LOCAL
1576 if (cur->func_nest_level < local_lvl) {
1577 /* New variable is declared as local,
1578 * and existing one is global, or local
1579 * from enclosing function.
1580 * Remove and save old one: */
1581 *var_pp = cur->next;
1582 cur->next = *G.shadowed_vars_pp;
1583 *G.shadowed_vars_pp = cur;
1584 /* bash 3.2.33(1) and exported vars:
1585 * # export z=z
1586 * # f() { local z=a; env | grep ^z; }
1587 * # f
1588 * z=a
1589 * # env | grep ^z
1590 * z=z
1591 */
1592 if (cur->flg_export)
1593 flg_export = 1;
1594 break;
1595 }
1596#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001597 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001598 free_and_exp:
1599 free(str);
1600 goto exp;
1601 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001602 if (cur->max_len != 0) {
1603 if (cur->max_len >= strlen(str)) {
1604 /* This one is from startup env, reuse space */
1605 strcpy(cur->varstr, str);
1606 goto free_and_exp;
1607 }
1608 } else {
1609 /* max_len == 0 signifies "malloced" var, which we can
1610 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001611 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001612 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001613 cur->max_len = 0;
1614 goto set_str_and_exp;
1615 }
1616
Denys Vlasenko295fef82009-06-03 12:47:26 +02001617 /* Not found - create new variable struct */
1618 cur = xzalloc(sizeof(*cur));
1619#if ENABLE_HUSH_LOCAL
1620 cur->func_nest_level = local_lvl;
1621#endif
1622 cur->next = *var_pp;
1623 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001624
1625 set_str_and_exp:
1626 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001627#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001628 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001629#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001630 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001631 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001632 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001633 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1634 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001635 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001636 if (flg_export == -1) {
1637 cur->flg_export = 0;
1638 /* unsetenv was already done */
1639 } else {
1640 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1641 return putenv(cur->varstr);
1642 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001643 }
1644 return 0;
1645}
1646
Denys Vlasenko6db47842009-09-05 20:15:17 +02001647/* Used at startup and after each cd */
1648static void set_pwd_var(int exp)
1649{
1650 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1651 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1652}
1653
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001654static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001655{
1656 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001657 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001658
1659 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001660 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001661 var_pp = &G.top_var;
1662 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001663 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1664 if (cur->flg_read_only) {
1665 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001666 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001667 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001668 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001669 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1670 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001671 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1672 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001673 if (!cur->max_len)
1674 free(cur->varstr);
1675 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001676 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001677 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001678 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001679 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001680 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001681}
1682
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001683static int unset_local_var(const char *name)
1684{
1685 return unset_local_var_len(name, strlen(name));
1686}
1687
1688static void unset_vars(char **strings)
1689{
1690 char **v;
1691
1692 if (!strings)
1693 return;
1694 v = strings;
1695 while (*v) {
1696 const char *eq = strchrnul(*v, '=');
1697 unset_local_var_len(*v, (int)(eq - *v));
1698 v++;
1699 }
1700 free(strings);
1701}
1702
Denys Vlasenko03dad222010-01-12 23:29:57 +01001703static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001704{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001705 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001706 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001707}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001708
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001709
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001710/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001711 * Helpers for "var1=val1 var2=val2 cmd" feature
1712 */
1713static void add_vars(struct variable *var)
1714{
1715 struct variable *next;
1716
1717 while (var) {
1718 next = var->next;
1719 var->next = G.top_var;
1720 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001721 if (var->flg_export) {
1722 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001723 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001724 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001725 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001726 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001727 var = next;
1728 }
1729}
1730
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001731static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001732{
1733 char **s;
1734 struct variable *old = NULL;
1735
1736 if (!strings)
1737 return old;
1738 s = strings;
1739 while (*s) {
1740 struct variable *var_p;
1741 struct variable **var_pp;
1742 char *eq;
1743
1744 eq = strchr(*s, '=');
1745 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001746 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001747 if (var_pp) {
1748 /* Remove variable from global linked list */
1749 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001750 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001751 *var_pp = var_p->next;
1752 /* Add it to returned list */
1753 var_p->next = old;
1754 old = var_p;
1755 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001756 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001757 }
1758 s++;
1759 }
1760 return old;
1761}
1762
1763
1764/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001765 * in_str support
1766 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001767static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001768{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001769 int ch = *i->p;
1770 if (ch != '\0') {
1771 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001772 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001773 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001774 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001775}
1776
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001777static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001778{
1779 return *i->p;
1780}
1781
1782#if ENABLE_HUSH_INTERACTIVE
1783
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001784static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001785{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001786 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001787 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001788 if (G.PS1 == NULL)
1789 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001790 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001791 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001792 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001793 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001794 if (G.PS2 == NULL)
1795 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001796}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001797
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001798static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001799{
1800 const char *prompt_str;
1801 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001802 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1803 /* Set up the prompt */
1804 if (promptmode == 0) { /* PS1 */
1805 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001806 /* bash uses $PWD value, even if it is set by user.
1807 * It uses current dir only if PWD is unset.
1808 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001809 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001810 prompt_str = G.PS1;
1811 } else
1812 prompt_str = G.PS2;
1813 } else
1814 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001815 debug_printf("result '%s'\n", prompt_str);
1816 return prompt_str;
1817}
1818
1819static void get_user_input(struct in_str *i)
1820{
1821 int r;
1822 const char *prompt_str;
1823
1824 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001825# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001826 /* Enable command line editing only while a command line
1827 * is actually being read */
1828 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001829 G.flag_SIGINT = 0;
1830 /* buglet: SIGINT will not make new prompt to appear _at once_,
1831 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001832 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001833 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001834 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001835 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001836 i->eof_flag = (r < 0);
1837 if (i->eof_flag) { /* EOF/error detected */
1838 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1839 G.user_input_buf[1] = '\0';
1840 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001841# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001842 do {
1843 G.flag_SIGINT = 0;
1844 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001845 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001846 G.user_input_buf[0] = r = fgetc(i->file);
1847 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001848//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001849 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001850 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001851# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001852 i->p = G.user_input_buf;
1853}
1854
1855#endif /* INTERACTIVE */
1856
1857/* This is the magic location that prints prompts
1858 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001859static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001860{
1861 int ch;
1862
1863 /* If there is data waiting, eat it up */
1864 if (i->p && *i->p) {
1865#if ENABLE_HUSH_INTERACTIVE
1866 take_cached:
1867#endif
1868 ch = *i->p++;
1869 if (i->eof_flag && !*i->p)
1870 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001871 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001872 } else {
1873 /* need to double check i->file because we might be doing something
1874 * more complicated by now, like sourcing or substituting. */
1875#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001876 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001877 do {
1878 get_user_input(i);
1879 } while (!*i->p); /* need non-empty line */
1880 i->promptmode = 1; /* PS2 */
1881 i->promptme = 0;
1882 goto take_cached;
1883 }
1884#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001885 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001886 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001887 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001888#if ENABLE_HUSH_INTERACTIVE
1889 if (ch == '\n')
1890 i->promptme = 1;
1891#endif
1892 return ch;
1893}
1894
Denis Vlasenko913a2012009-04-05 22:17:04 +00001895/* All callers guarantee this routine will never
1896 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001897 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001898static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001899{
1900 int ch;
1901 if (i->p && *i->p) {
1902 if (i->eof_flag && !i->p[1])
1903 return EOF;
1904 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001905 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001906 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001907 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001908 i->eof_flag = (ch == EOF);
1909 i->peek_buf[0] = ch;
1910 i->peek_buf[1] = '\0';
1911 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001912 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001913 return ch;
1914}
1915
1916static void setup_file_in_str(struct in_str *i, FILE *f)
1917{
1918 i->peek = file_peek;
1919 i->get = file_get;
1920#if ENABLE_HUSH_INTERACTIVE
1921 i->promptme = 1;
1922 i->promptmode = 0; /* PS1 */
1923#endif
1924 i->file = f;
1925 i->p = NULL;
1926}
1927
1928static void setup_string_in_str(struct in_str *i, const char *s)
1929{
1930 i->peek = static_peek;
1931 i->get = static_get;
1932#if ENABLE_HUSH_INTERACTIVE
1933 i->promptme = 1;
1934 i->promptmode = 0; /* PS1 */
1935#endif
1936 i->p = s;
1937 i->eof_flag = 0;
1938}
1939
1940
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001941/*
1942 * o_string support
1943 */
1944#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001945
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001946static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001947{
1948 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02001949 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001950 if (o->data)
1951 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001952}
1953
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001954static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001955{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001956 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001957 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001958}
1959
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001960static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1961{
1962 free(o->data);
1963}
1964
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001965static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001966{
1967 if (o->length + len > o->maxlen) {
1968 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1969 o->data = xrealloc(o->data, 1 + o->maxlen);
1970 }
1971}
1972
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001973static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001974{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001975 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1976 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001977 o->data[o->length] = ch;
1978 o->length++;
1979 o->data[o->length] = '\0';
1980}
1981
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001982static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001983{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001984 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001985 memcpy(&o->data[o->length], str, len);
1986 o->length += len;
1987 o->data[o->length] = '\0';
1988}
1989
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001990static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001991{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001992 o_addblock(o, str, strlen(str));
1993}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02001994
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001995#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001996static void nommu_addchr(o_string *o, int ch)
1997{
1998 if (o)
1999 o_addchr(o, ch);
2000}
2001#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002002# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002003#endif
2004
2005static void o_addstr_with_NUL(o_string *o, const char *str)
2006{
2007 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002008}
2009
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002010/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002011 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002012 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2013 * Apparently, on unquoted $v bash still does globbing
2014 * ("v='*.txt'; echo $v" prints all .txt files),
2015 * but NOT brace expansion! Thus, there should be TWO independent
2016 * quoting mechanisms on $v expansion side: one protects
2017 * $v from brace expansion, and other additionally protects "$v" against globbing.
2018 * We have only second one.
2019 */
2020
Denys Vlasenko9e800222010-10-03 14:28:04 +02002021#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002022# define MAYBE_BRACES "{}"
2023#else
2024# define MAYBE_BRACES ""
2025#endif
2026
Eric Andersen25f27032001-04-26 23:22:31 +00002027/* My analysis of quoting semantics tells me that state information
2028 * is associated with a destination, not a source.
2029 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002030static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002031{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002032 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002033 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002034 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002035 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002036 o_grow_by(o, sz);
2037 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002038 o->data[o->length] = '\\';
2039 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002040 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002041 o->data[o->length] = ch;
2042 o->length++;
2043 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002044}
2045
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002046static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002047{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002048 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002049 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2050 && strchr("*?[\\" MAYBE_BRACES, ch)
2051 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002052 sz++;
2053 o->data[o->length] = '\\';
2054 o->length++;
2055 }
2056 o_grow_by(o, sz);
2057 o->data[o->length] = ch;
2058 o->length++;
2059 o->data[o->length] = '\0';
2060}
2061
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002062static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002063{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002064 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002065 char ch;
2066 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002067 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002068 if (ordinary_cnt > len) /* paranoia */
2069 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002070 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002071 if (ordinary_cnt == len)
2072 return;
2073 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002074 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002075
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002076 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002077 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002078 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002079 sz++;
2080 o->data[o->length] = '\\';
2081 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002082 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002083 o_grow_by(o, sz);
2084 o->data[o->length] = ch;
2085 o->length++;
2086 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002087 }
2088}
2089
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002090static void o_addQblock(o_string *o, const char *str, int len)
2091{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002092 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002093 o_addblock(o, str, len);
2094 return;
2095 }
2096 o_addqblock(o, str, len);
2097}
2098
Denys Vlasenko38292b62010-09-05 14:49:40 +02002099static void o_addQstr(o_string *o, const char *str)
2100{
2101 o_addQblock(o, str, strlen(str));
2102}
2103
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002104/* A special kind of o_string for $VAR and `cmd` expansion.
2105 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002106 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002107 * list[i] contains an INDEX (int!) into this string data.
2108 * It means that if list[] needs to grow, data needs to be moved higher up
2109 * but list[i]'s need not be modified.
2110 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002111 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002112 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2113 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002114#if DEBUG_EXPAND || DEBUG_GLOB
2115static void debug_print_list(const char *prefix, o_string *o, int n)
2116{
2117 char **list = (char**)o->data;
2118 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2119 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002120
2121 indent();
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002122 fprintf(stderr, "%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 +02002123 prefix, list, n, string_start, o->length, o->maxlen,
2124 !!(o->o_expflags & EXP_FLAG_GLOB),
2125 o->has_quoted_part,
2126 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002127 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002128 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002129 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2130 o->data + (int)list[i] + string_start,
2131 o->data + (int)list[i] + string_start);
2132 i++;
2133 }
2134 if (n) {
2135 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002136 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002137 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002138 }
2139}
2140#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002141# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002142#endif
2143
2144/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2145 * in list[n] so that it points past last stored byte so far.
2146 * It returns n+1. */
2147static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002148{
2149 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002150 int string_start;
2151 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002152
2153 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002154 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2155 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002156 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002157 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002158 /* list[n] points to string_start, make space for 16 more pointers */
2159 o->maxlen += 0x10 * sizeof(list[0]);
2160 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002161 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002162 memmove(list + n + 0x10, list + n, string_len);
2163 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002164 } else {
2165 debug_printf_list("list[%d]=%d string_start=%d\n",
2166 n, string_len, string_start);
2167 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002168 } else {
2169 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002170 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2171 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002172 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2173 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002174 o->has_empty_slot = 0;
2175 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002176 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002177 return n + 1;
2178}
2179
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002180/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002181static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002182{
2183 char **list = (char**)o->data;
2184 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2185
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002186 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002187}
2188
Denys Vlasenko9e800222010-10-03 14:28:04 +02002189#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002190/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2191 * first, it processes even {a} (no commas), second,
2192 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002193 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002194 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002195
2196/* Helper */
2197static int glob_needed(const char *s)
2198{
2199 while (*s) {
2200 if (*s == '\\') {
2201 if (!s[1])
2202 return 0;
2203 s += 2;
2204 continue;
2205 }
2206 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2207 return 1;
2208 s++;
2209 }
2210 return 0;
2211}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002212/* Return pointer to next closing brace or to comma */
2213static const char *next_brace_sub(const char *cp)
2214{
2215 unsigned depth = 0;
2216 cp++;
2217 while (*cp != '\0') {
2218 if (*cp == '\\') {
2219 if (*++cp == '\0')
2220 break;
2221 cp++;
2222 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002223 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002224 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002225 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002226 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002227 depth++;
2228 }
2229
2230 return *cp != '\0' ? cp : NULL;
2231}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002232/* Recursive brace globber. Note: may garble pattern[]. */
2233static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002234{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002235 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002236 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002237 const char *next;
2238 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002239 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002240 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002241
2242 debug_printf_glob("glob_brace('%s')\n", pattern);
2243
2244 begin = pattern;
2245 while (1) {
2246 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002247 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002248 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002249 /* Find the first sub-pattern and at the same time
2250 * find the rest after the closing brace */
2251 next = next_brace_sub(begin);
2252 if (next == NULL) {
2253 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002254 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002255 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002256 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002257 /* "{abc}" with no commas - illegal
2258 * brace expr, disregard and skip it */
2259 begin = next + 1;
2260 continue;
2261 }
2262 break;
2263 }
2264 if (*begin == '\\' && begin[1] != '\0')
2265 begin++;
2266 begin++;
2267 }
2268 debug_printf_glob("begin:%s\n", begin);
2269 debug_printf_glob("next:%s\n", next);
2270
2271 /* Now find the end of the whole brace expression */
2272 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002273 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002274 rest = next_brace_sub(rest);
2275 if (rest == NULL) {
2276 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002277 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002278 }
2279 debug_printf_glob("rest:%s\n", rest);
2280 }
2281 rest_len = strlen(++rest) + 1;
2282
2283 /* We are sure the brace expression is well-formed */
2284
2285 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002286 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002287
2288 /* We have a brace expression. BEGIN points to the opening {,
2289 * NEXT points past the terminator of the first element, and REST
2290 * points past the final }. We will accumulate result names from
2291 * recursive runs for each brace alternative in the buffer using
2292 * GLOB_APPEND. */
2293
2294 p = begin + 1;
2295 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002296 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002297 memcpy(
2298 mempcpy(
2299 mempcpy(new_pattern_buf,
2300 /* We know the prefix for all sub-patterns */
2301 pattern, begin - pattern),
2302 p, next - p),
2303 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002304
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002305 /* Note: glob_brace() may garble new_pattern_buf[].
2306 * That's why we re-copy prefix every time (1st memcpy above).
2307 */
2308 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002309 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002310 /* We saw the last entry */
2311 break;
2312 }
2313 p = next + 1;
2314 next = next_brace_sub(next);
2315 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002316 free(new_pattern_buf);
2317 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002318
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002319 simple_glob:
2320 {
2321 int gr;
2322 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002323
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002324 memset(&globdata, 0, sizeof(globdata));
2325 gr = glob(pattern, 0, NULL, &globdata);
2326 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2327 if (gr != 0) {
2328 if (gr == GLOB_NOMATCH) {
2329 globfree(&globdata);
2330 /* NB: garbles parameter */
2331 unbackslash(pattern);
2332 o_addstr_with_NUL(o, pattern);
2333 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2334 return o_save_ptr_helper(o, n);
2335 }
2336 if (gr == GLOB_NOSPACE)
2337 bb_error_msg_and_die(bb_msg_memory_exhausted);
2338 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2339 * but we didn't specify it. Paranoia again. */
2340 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2341 }
2342 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2343 char **argv = globdata.gl_pathv;
2344 while (1) {
2345 o_addstr_with_NUL(o, *argv);
2346 n = o_save_ptr_helper(o, n);
2347 argv++;
2348 if (!*argv)
2349 break;
2350 }
2351 }
2352 globfree(&globdata);
2353 }
2354 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002355}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002356/* Performs globbing on last list[],
2357 * saving each result as a new list[].
2358 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002359static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002360{
2361 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002362
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002363 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002364 if (!o->data)
2365 return o_save_ptr_helper(o, n);
2366 pattern = o->data + o_get_last_ptr(o, n);
2367 debug_printf_glob("glob pattern '%s'\n", pattern);
2368 if (!glob_needed(pattern)) {
2369 /* unbackslash last string in o in place, fix length */
2370 o->length = unbackslash(pattern) - o->data;
2371 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2372 return o_save_ptr_helper(o, n);
2373 }
2374
2375 copy = xstrdup(pattern);
2376 /* "forget" pattern in o */
2377 o->length = pattern - o->data;
2378 n = glob_brace(copy, o, n);
2379 free(copy);
2380 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002381 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002382 return n;
2383}
2384
Denys Vlasenko238081f2010-10-03 14:26:26 +02002385#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002386
2387/* Helper */
2388static int glob_needed(const char *s)
2389{
2390 while (*s) {
2391 if (*s == '\\') {
2392 if (!s[1])
2393 return 0;
2394 s += 2;
2395 continue;
2396 }
2397 if (*s == '*' || *s == '[' || *s == '?')
2398 return 1;
2399 s++;
2400 }
2401 return 0;
2402}
2403/* Performs globbing on last list[],
2404 * saving each result as a new list[].
2405 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002406static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002407{
2408 glob_t globdata;
2409 int gr;
2410 char *pattern;
2411
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002412 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002413 if (!o->data)
2414 return o_save_ptr_helper(o, n);
2415 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002416 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002417 if (!glob_needed(pattern)) {
2418 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002419 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002420 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002421 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002422 return o_save_ptr_helper(o, n);
2423 }
2424
2425 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002426 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2427 * If we glob "*.\*" and don't find anything, we need
2428 * to fall back to using literal "*.*", but GLOB_NOCHECK
2429 * will return "*.\*"!
2430 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002431 gr = glob(pattern, 0, NULL, &globdata);
2432 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002433 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002434 if (gr == GLOB_NOMATCH) {
2435 globfree(&globdata);
2436 goto literal;
2437 }
2438 if (gr == GLOB_NOSPACE)
2439 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002440 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2441 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002442 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002443 }
2444 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2445 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002446 /* "forget" pattern in o */
2447 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002448 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002449 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002450 n = o_save_ptr_helper(o, n);
2451 argv++;
2452 if (!*argv)
2453 break;
2454 }
2455 }
2456 globfree(&globdata);
2457 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002458 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002459 return n;
2460}
2461
Denys Vlasenko238081f2010-10-03 14:26:26 +02002462#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002463
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002464/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002465 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002466static int o_save_ptr(o_string *o, int n)
2467{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002468 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002469 /* If o->has_empty_slot, list[n] was already globbed
2470 * (if it was requested back then when it was filled)
2471 * so don't do that again! */
2472 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002473 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002474 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002475 return o_save_ptr_helper(o, n);
2476}
2477
2478/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002479static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002480{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002481 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002482 int string_start;
2483
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002484 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2485 if (DEBUG_EXPAND)
2486 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002487 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002488 list = (char**)o->data;
2489 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2490 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002491 while (n) {
2492 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002493 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002494 }
2495 return list;
2496}
2497
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002498static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002499
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002500/* Returns pi->next - next pipe in the list */
2501static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002502{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002503 struct pipe *next;
2504 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002505
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002506 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002507 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002508 struct command *command;
2509 struct redir_struct *r, *rnext;
2510
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002511 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002512 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002513 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002514 if (DEBUG_CLEAN) {
2515 int a;
2516 char **p;
2517 for (a = 0, p = command->argv; *p; a++, p++) {
2518 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2519 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002520 }
2521 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002522 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002523 }
2524 /* not "else if": on syntax error, we may have both! */
2525 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002526 debug_printf_clean(" begin group (cmd_type:%d)\n",
2527 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002528 free_pipe_list(command->group);
2529 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002530 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002531 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002532 /* else is crucial here.
2533 * If group != NULL, child_func is meaningless */
2534#if ENABLE_HUSH_FUNCTIONS
2535 else if (command->child_func) {
2536 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2537 command->child_func->parent_cmd = NULL;
2538 }
2539#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002540#if !BB_MMU
2541 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002542 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002543#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002544 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002545 debug_printf_clean(" redirect %d%s",
2546 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002547 /* guard against the case >$FOO, where foo is unset or blank */
2548 if (r->rd_filename) {
2549 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2550 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002551 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002552 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002553 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002554 rnext = r->next;
2555 free(r);
2556 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002557 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002558 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002559 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002560 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002561#if ENABLE_HUSH_JOB
2562 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002563 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002564#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002565
2566 next = pi->next;
2567 free(pi);
2568 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002569}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002570
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002571static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002572{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002573 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002574#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002575 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002576#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002577 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002578 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002579 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002580}
2581
2582
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002583/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002584
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002585static struct pipe *new_pipe(void)
2586{
Eric Andersen25f27032001-04-26 23:22:31 +00002587 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002588 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002589 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002590 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002591 return pi;
2592}
2593
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002594/* Command (member of a pipe) is complete, or we start a new pipe
2595 * if ctx->command is NULL.
2596 * No errors possible here.
2597 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002598static int done_command(struct parse_context *ctx)
2599{
2600 /* The command is really already in the pipe structure, so
2601 * advance the pipe counter and make a new, null command. */
2602 struct pipe *pi = ctx->pipe;
2603 struct command *command = ctx->command;
2604
2605 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002606 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002607 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002608 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002609 }
2610 pi->num_cmds++;
2611 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002612 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002613 } else {
2614 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2615 }
2616
2617 /* Only real trickiness here is that the uncommitted
2618 * command structure is not counted in pi->num_cmds. */
2619 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002620 ctx->command = command = &pi->cmds[pi->num_cmds];
2621 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002622 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002623 return pi->num_cmds; /* used only for 0/nonzero check */
2624}
2625
2626static void done_pipe(struct parse_context *ctx, pipe_style type)
2627{
2628 int not_null;
2629
2630 debug_printf_parse("done_pipe entered, followup %d\n", type);
2631 /* Close previous command */
2632 not_null = done_command(ctx);
2633 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002634#if HAS_KEYWORDS
2635 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2636 ctx->ctx_inverted = 0;
2637 ctx->pipe->res_word = ctx->ctx_res_w;
2638#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002639
2640 /* Without this check, even just <enter> on command line generates
2641 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002642 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002643 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002644#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002645 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002646#endif
2647#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002648 || ctx->ctx_res_w == RES_DONE
2649 || ctx->ctx_res_w == RES_FOR
2650 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002651#endif
2652#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002653 || ctx->ctx_res_w == RES_ESAC
2654#endif
2655 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002656 struct pipe *new_p;
2657 debug_printf_parse("done_pipe: adding new pipe: "
2658 "not_null:%d ctx->ctx_res_w:%d\n",
2659 not_null, ctx->ctx_res_w);
2660 new_p = new_pipe();
2661 ctx->pipe->next = new_p;
2662 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002663 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002664 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002665 * This is used to control execution.
2666 * RES_FOR and RES_IN are NOT sticky (needed to support
2667 * cases where variable or value happens to match a keyword):
2668 */
2669#if ENABLE_HUSH_LOOPS
2670 if (ctx->ctx_res_w == RES_FOR
2671 || ctx->ctx_res_w == RES_IN)
2672 ctx->ctx_res_w = RES_NONE;
2673#endif
2674#if ENABLE_HUSH_CASE
2675 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002676 ctx->ctx_res_w = RES_CASE_BODY;
2677 if (ctx->ctx_res_w == RES_CASE)
2678 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002679#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002680 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002681 /* Create the memory for command, roughly:
2682 * ctx->pipe->cmds = new struct command;
2683 * ctx->command = &ctx->pipe->cmds[0];
2684 */
2685 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002686 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002687 }
2688 debug_printf_parse("done_pipe return\n");
2689}
2690
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002691static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002692{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002693 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002694 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002695 /* Create the memory for command, roughly:
2696 * ctx->pipe->cmds = new struct command;
2697 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002698 */
2699 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002700}
2701
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002702/* If a reserved word is found and processed, parse context is modified
2703 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002704 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002705#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002706struct reserved_combo {
2707 char literal[6];
2708 unsigned char res;
2709 unsigned char assignment_flag;
2710 int flag;
2711};
2712enum {
2713 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002714# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002715 FLAG_IF = (1 << RES_IF ),
2716 FLAG_THEN = (1 << RES_THEN ),
2717 FLAG_ELIF = (1 << RES_ELIF ),
2718 FLAG_ELSE = (1 << RES_ELSE ),
2719 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002720# endif
2721# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002722 FLAG_FOR = (1 << RES_FOR ),
2723 FLAG_WHILE = (1 << RES_WHILE),
2724 FLAG_UNTIL = (1 << RES_UNTIL),
2725 FLAG_DO = (1 << RES_DO ),
2726 FLAG_DONE = (1 << RES_DONE ),
2727 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002728# endif
2729# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002730 FLAG_MATCH = (1 << RES_MATCH),
2731 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002732# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002733 FLAG_START = (1 << RES_XXXX ),
2734};
2735
2736static const struct reserved_combo* match_reserved_word(o_string *word)
2737{
Eric Andersen25f27032001-04-26 23:22:31 +00002738 /* Mostly a list of accepted follow-up reserved words.
2739 * FLAG_END means we are done with the sequence, and are ready
2740 * to turn the compound list into a command.
2741 * FLAG_START means the word must start a new compound list.
2742 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002743 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002744# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002745 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2746 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2747 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2748 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2749 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2750 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002751# endif
2752# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002753 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2754 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2755 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2756 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2757 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2758 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002759# endif
2760# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002761 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2762 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002763# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002764 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002765 const struct reserved_combo *r;
2766
2767 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2768 if (strcmp(word->data, r->literal) == 0)
2769 return r;
2770 }
2771 return NULL;
2772}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002773/* Return 0: not a keyword, 1: keyword
2774 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002775static int reserved_word(o_string *word, struct parse_context *ctx)
2776{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002777# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002778 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002779 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002780 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002781# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002782 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002783
Denys Vlasenko38292b62010-09-05 14:49:40 +02002784 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002785 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002786 r = match_reserved_word(word);
2787 if (!r)
2788 return 0;
2789
2790 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002791# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002792 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2793 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002794 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002795 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002796# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002797 if (r->flag == 0) { /* '!' */
2798 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002799 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002800 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002801 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002802 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002803 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002804 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002805 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002806 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002807
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002808 old = xmalloc(sizeof(*old));
2809 debug_printf_parse("push stack %p\n", old);
2810 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002811 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002812 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002813 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002814 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002815 ctx->ctx_res_w = RES_SNTX;
2816 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002817 } else {
2818 /* "{...} fi" is ok. "{...} if" is not
2819 * Example:
2820 * if { echo foo; } then { echo bar; } fi */
2821 if (ctx->command->group)
2822 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002823 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002824
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002825 ctx->ctx_res_w = r->res;
2826 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002827 word->o_assignment = r->assignment_flag;
2828
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002829 if (ctx->old_flag & FLAG_END) {
2830 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002831
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002832 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002833 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002834 old = ctx->stack;
2835 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002836 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002837# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002838 o_addstr(&old->as_string, ctx->as_string.data);
2839 o_free_unsafe(&ctx->as_string);
2840 old->command->group_as_string = xstrdup(old->as_string.data);
2841 debug_printf_parse("pop, remembering as:'%s'\n",
2842 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002843# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002844 *ctx = *old; /* physical copy */
2845 free(old);
2846 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002847 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002848}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002849#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00002850
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002851/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002852 * Normal return is 0. Syntax errors return 1.
2853 * Note: on return, word is reset, but not o_free'd!
2854 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002855static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002856{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002857 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00002858
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002859 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02002860 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002861 debug_printf_parse("done_word return 0: true null, ignored\n");
2862 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002863 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002864
Eric Andersen25f27032001-04-26 23:22:31 +00002865 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002866 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2867 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002868 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2869 * "2.7 Redirection
2870 * ...the word that follows the redirection operator
2871 * shall be subjected to tilde expansion, parameter expansion,
2872 * command substitution, arithmetic expansion, and quote
2873 * removal. Pathname expansion shall not be performed
2874 * on the word by a non-interactive shell; an interactive
2875 * shell may perform it, but shall do so only when
2876 * the expansion would result in one word."
2877 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002878 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002879 /* Cater for >\file case:
2880 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2881 * Same with heredocs:
2882 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2883 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002884 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2885 unbackslash(ctx->pending_redirect->rd_filename);
2886 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02002887 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002888 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2889 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002890 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002891 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002892 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002893 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002894 /* If this word wasn't an assignment, next ones definitely
2895 * can't be assignments. Even if they look like ones. */
2896 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2897 && word->o_assignment != WORD_IS_KEYWORD
2898 ) {
2899 word->o_assignment = NOT_ASSIGNMENT;
2900 } else {
2901 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2902 command->assignment_cnt++;
2903 word->o_assignment = MAYBE_ASSIGNMENT;
2904 }
2905
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002906#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002907# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00002908 if (ctx->ctx_dsemicolon
2909 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2910 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00002911 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002912 /* ctx->ctx_res_w = RES_MATCH; */
2913 ctx->ctx_dsemicolon = 0;
2914 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002915# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002916 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002917# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002918 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2919 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002920# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002921# if ENABLE_HUSH_CASE
2922 && ctx->ctx_res_w != RES_CASE
2923# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002924 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002925 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002926 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002927 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002928 debug_printf_parse("done_word return %d\n",
2929 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002930 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002931 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002932# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002933 if (strcmp(word->data, "[[") == 0) {
2934 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2935 }
2936 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002937# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002938 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002939#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00002940 if (command->group) {
2941 /* "{ echo foo; } echo bar" - bad */
2942 syntax_error_at(word->data);
2943 debug_printf_parse("done_word return 1: syntax error, "
2944 "groups and arglists don't mix\n");
2945 return 1;
2946 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02002947 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00002948 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2949 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002950 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002951 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002952 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002953 char *p = word->data;
2954 while (p[0] == SPECIAL_VAR_SYMBOL
2955 && (p[1] & 0x7f) == '@'
2956 && p[2] == SPECIAL_VAR_SYMBOL
2957 ) {
2958 p += 3;
2959 }
2960 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002961 /* saw no "$@", or not only "$@" but some
2962 * real text is there too */
2963 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002964 * e.g. "", $empty"" etc to not disappear */
2965 o_addchr(word, SPECIAL_VAR_SYMBOL);
2966 o_addchr(word, SPECIAL_VAR_SYMBOL);
2967 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002968 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002969 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002970 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002971 }
Eric Andersen25f27032001-04-26 23:22:31 +00002972
Denis Vlasenko06810332007-05-21 23:30:54 +00002973#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002974 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02002975 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002976 || !is_well_formed_var_name(command->argv[0], '\0')
2977 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002978 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002979 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002980 return 1;
2981 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002982 /* Force FOR to have just one word (variable name) */
2983 /* NB: basically, this makes hush see "for v in ..."
2984 * syntax as if it is "for v; in ...". FOR and IN become
2985 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002986 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002987 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002988#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002989#if ENABLE_HUSH_CASE
2990 /* Force CASE to have just one word */
2991 if (ctx->ctx_res_w == RES_CASE) {
2992 done_pipe(ctx, PIPE_SEQ);
2993 }
2994#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002995
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002996 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002997
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002998 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002999 return 0;
3000}
3001
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003002
3003/* Peek ahead in the input to find out if we have a "&n" construct,
3004 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003005 * Return:
3006 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3007 * REDIRFD_SYNTAX_ERR if syntax error,
3008 * REDIRFD_TO_FILE if no & was seen,
3009 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003010 */
3011#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003012#define parse_redir_right_fd(as_string, input) \
3013 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003014#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003015static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003016{
3017 int ch, d, ok;
3018
3019 ch = i_peek(input);
3020 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003021 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003022
3023 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003024 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003025 ch = i_peek(input);
3026 if (ch == '-') {
3027 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003028 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003029 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003030 }
3031 d = 0;
3032 ok = 0;
3033 while (ch != EOF && isdigit(ch)) {
3034 d = d*10 + (ch-'0');
3035 ok = 1;
3036 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003037 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003038 ch = i_peek(input);
3039 }
3040 if (ok) return d;
3041
3042//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3043
3044 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003045 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003046}
3047
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003048/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003049 */
3050static int parse_redirect(struct parse_context *ctx,
3051 int fd,
3052 redir_type style,
3053 struct in_str *input)
3054{
3055 struct command *command = ctx->command;
3056 struct redir_struct *redir;
3057 struct redir_struct **redirp;
3058 int dup_num;
3059
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003060 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003061 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003062 /* Check for a '>&1' type redirect */
3063 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3064 if (dup_num == REDIRFD_SYNTAX_ERR)
3065 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003066 } else {
3067 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003068 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003069 if (dup_num) { /* <<-... */
3070 ch = i_getch(input);
3071 nommu_addchr(&ctx->as_string, ch);
3072 ch = i_peek(input);
3073 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003074 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003075
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003076 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003077 int ch = i_peek(input);
3078 if (ch == '|') {
3079 /* >|FILE redirect ("clobbering" >).
3080 * Since we do not support "set -o noclobber" yet,
3081 * >| and > are the same for now. Just eat |.
3082 */
3083 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003084 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003085 }
3086 }
3087
3088 /* Create a new redir_struct and append it to the linked list */
3089 redirp = &command->redirects;
3090 while ((redir = *redirp) != NULL) {
3091 redirp = &(redir->next);
3092 }
3093 *redirp = redir = xzalloc(sizeof(*redir));
3094 /* redir->next = NULL; */
3095 /* redir->rd_filename = NULL; */
3096 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003097 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003098
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003099 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3100 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003101
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003102 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003103 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003104 /* Erik had a check here that the file descriptor in question
3105 * is legit; I postpone that to "run time"
3106 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003107 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3108 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003109 } else {
3110 /* Set ctx->pending_redirect, so we know what to do at the
3111 * end of the next parsed word. */
3112 ctx->pending_redirect = redir;
3113 }
3114 return 0;
3115}
3116
Eric Andersen25f27032001-04-26 23:22:31 +00003117/* If a redirect is immediately preceded by a number, that number is
3118 * supposed to tell which file descriptor to redirect. This routine
3119 * looks for such preceding numbers. In an ideal world this routine
3120 * needs to handle all the following classes of redirects...
3121 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3122 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3123 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3124 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003125 *
3126 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3127 * "2.7 Redirection
3128 * ... If n is quoted, the number shall not be recognized as part of
3129 * the redirection expression. For example:
3130 * echo \2>a
3131 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003132 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003133 *
3134 * A -1 return means no valid number was found,
3135 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003136 */
3137static int redirect_opt_num(o_string *o)
3138{
3139 int num;
3140
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003141 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003142 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003143 num = bb_strtou(o->data, NULL, 10);
3144 if (errno || num < 0)
3145 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003146 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003147 return num;
3148}
3149
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003150#if BB_MMU
3151#define fetch_till_str(as_string, input, word, skip_tabs) \
3152 fetch_till_str(input, word, skip_tabs)
3153#endif
3154static char *fetch_till_str(o_string *as_string,
3155 struct in_str *input,
3156 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003157 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003158{
3159 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003160 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003161 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003162 int ch;
3163
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003164 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003165 while (1) {
3166 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003167 if (ch != EOF)
3168 nommu_addchr(as_string, ch);
3169 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003170 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3171 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003172 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3173 heredoc.data[past_EOL] = '\0';
3174 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3175 return heredoc.data;
3176 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003177 while (ch == '\n') {
3178 o_addchr(&heredoc, ch);
3179 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003180 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003181 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003182 do {
3183 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003184 if (ch != EOF)
3185 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003186 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003187 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003188 }
3189 if (ch == EOF) {
3190 o_free_unsafe(&heredoc);
3191 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003192 }
3193 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003194 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003195 if (prev == '\\' && ch == '\\')
3196 /* Correctly handle foo\\<eol> (not a line cont.) */
3197 prev = 0; /* not \ */
3198 else
3199 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003200 }
3201}
3202
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003203/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3204 * and load them all. There should be exactly heredoc_cnt of them.
3205 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003206static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3207{
3208 struct pipe *pi = ctx->list_head;
3209
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003210 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003211 int i;
3212 struct command *cmd = pi->cmds;
3213
3214 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3215 pi->num_cmds,
3216 cmd->argv ? cmd->argv[0] : "NONE");
3217 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003218 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003219
3220 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3221 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003222 while (redir) {
3223 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003224 char *p;
3225
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003226 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003227 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003228 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003229 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003230 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003231 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003232 return 1;
3233 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003234 free(redir->rd_filename);
3235 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003236 heredoc_cnt--;
3237 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003238 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003239 }
3240 cmd++;
3241 }
3242 pi = pi->next;
3243 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003244#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003245 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003246 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003247 bb_error_msg_and_die("heredoc BUG 2");
3248#endif
3249 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003250}
3251
3252
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003253static int run_list(struct pipe *pi);
3254#if BB_MMU
3255#define parse_stream(pstring, input, end_trigger) \
3256 parse_stream(input, end_trigger)
3257#endif
3258static struct pipe *parse_stream(char **pstring,
3259 struct in_str *input,
3260 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003261
Eric Andersen25f27032001-04-26 23:22:31 +00003262
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003263#if !ENABLE_HUSH_FUNCTIONS
3264#define parse_group(dest, ctx, input, ch) \
3265 parse_group(ctx, input, ch)
3266#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003267static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003268 struct in_str *input, int ch)
3269{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003270 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003271 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003272 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003273 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003274 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003275 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003276
3277 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003278#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003279 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003280 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003281 if (done_word(dest, ctx))
3282 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003283 if (!command->argv)
3284 goto skip; /* (... */
3285 if (command->argv[1]) { /* word word ... (... */
3286 syntax_error_unexpected_ch('(');
3287 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003288 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003289 /* it is "word(..." or "word (..." */
3290 do
3291 ch = i_getch(input);
3292 while (ch == ' ' || ch == '\t');
3293 if (ch != ')') {
3294 syntax_error_unexpected_ch(ch);
3295 return 1;
3296 }
3297 nommu_addchr(&ctx->as_string, ch);
3298 do
3299 ch = i_getch(input);
3300 while (ch == ' ' || ch == '\t' || ch == '\n');
3301 if (ch != '{') {
3302 syntax_error_unexpected_ch(ch);
3303 return 1;
3304 }
3305 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003306 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003307 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003308 }
3309#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003310
3311#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003312 if (command->argv /* word [word]{... */
3313 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003314 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003315 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003316 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003317 debug_printf_parse("parse_group return 1: "
3318 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003319 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003320 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003321#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003322
3323#if ENABLE_HUSH_FUNCTIONS
3324 skip:
3325#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003326 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003327 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003328 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003329 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003330 } else {
3331 /* bash does not allow "{echo...", requires whitespace */
3332 ch = i_getch(input);
3333 if (ch != ' ' && ch != '\t' && ch != '\n') {
3334 syntax_error_unexpected_ch(ch);
3335 return 1;
3336 }
3337 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003338 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003339
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003340 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003341#if BB_MMU
3342# define as_string NULL
3343#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003344 char *as_string = NULL;
3345#endif
3346 pipe_list = parse_stream(&as_string, input, endch);
3347#if !BB_MMU
3348 if (as_string)
3349 o_addstr(&ctx->as_string, as_string);
3350#endif
3351 /* empty ()/{} or parse error? */
3352 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003353 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003354 if (!BB_MMU)
3355 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003356 debug_printf_parse("parse_group return 1: "
3357 "parse_stream returned %p\n", pipe_list);
3358 return 1;
3359 }
3360 command->group = pipe_list;
3361#if !BB_MMU
3362 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3363 command->group_as_string = as_string;
3364 debug_printf_parse("end of group, remembering as:'%s'\n",
3365 command->group_as_string);
3366#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003367#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003368 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003369 debug_printf_parse("parse_group return 0\n");
3370 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003371 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003372}
3373
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003374#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003375/* Subroutines for copying $(...) and `...` things */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003376static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003377/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003378static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003379{
3380 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003381 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003382 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003383 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003384 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003385 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003386 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003387 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003388 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003389 }
3390}
3391/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003392static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003393{
3394 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003395 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003396 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003397 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003398 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003399 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003400 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003401 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003402 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003403 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003404 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003405 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003406 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003407 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003408 add_till_backquote(dest, input, /*in_dquote:*/ 1);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003409 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003410 continue;
3411 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003412 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003413 }
3414}
3415/* Process `cmd` - copy contents until "`" is seen. Complicated by
3416 * \` quoting.
3417 * "Within the backquoted style of command substitution, backslash
3418 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3419 * The search for the matching backquote shall be satisfied by the first
3420 * backquote found without a preceding backslash; during this search,
3421 * if a non-escaped backquote is encountered within a shell comment,
3422 * a here-document, an embedded command substitution of the $(command)
3423 * form, or a quoted string, undefined results occur. A single-quoted
3424 * or double-quoted string that begins, but does not end, within the
3425 * "`...`" sequence produces undefined results."
3426 * Example Output
3427 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3428 */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003429static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003430{
3431 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003432 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003433 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003434 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003435 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003436 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3437 ch = i_getch(input);
3438 if (ch != '`'
3439 && ch != '$'
3440 && ch != '\\'
3441 && (!in_dquote || ch != '"')
3442 ) {
3443 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003444 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003445 }
3446 if (ch == EOF) {
3447 syntax_error_unterm_ch('`');
3448 /*xfunc_die(); - redundant */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003449 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003450 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003451 }
3452}
3453/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3454 * quoting and nested ()s.
3455 * "With the $(command) style of command substitution, all characters
3456 * following the open parenthesis to the matching closing parenthesis
3457 * constitute the command. Any valid shell script can be used for command,
3458 * except a script consisting solely of redirections which produces
3459 * unspecified results."
3460 * Example Output
3461 * echo $(echo '(TEST)' BEST) (TEST) BEST
3462 * echo $(echo 'TEST)' BEST) TEST) BEST
3463 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003464 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003465 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003466 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003467 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3468 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003469 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003470#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003471static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003472{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003473 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003474 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003475# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003476 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003477# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003478 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3479
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003480 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003481 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003482 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003483 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003484 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003485 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003486 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003487 if (!dbl)
3488 break;
3489 /* we look for closing )) of $((EXPR)) */
3490 if (i_peek(input) == end_ch) {
3491 i_getch(input); /* eat second ')' */
3492 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003493 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003494 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003495 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003496 if (ch == '(' || ch == '{') {
3497 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003498 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003499 o_addchr(dest, ch);
3500 continue;
3501 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003502 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003503 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003504 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003505 continue;
3506 }
3507 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003508 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003509 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003510 continue;
3511 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003512 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003513 add_till_backquote(dest, input, /*in_dquote:*/ 0);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003514 o_addchr(dest, ch);
3515 continue;
3516 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003517 if (ch == '\\') {
3518 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003519 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003520 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003521 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003522 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003523 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003524 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003525 continue;
3526 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003527 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003528 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003529}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003530#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003531
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003532/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003533#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003534#define parse_dollar(as_string, dest, input, quote_mask) \
3535 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003536#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003537#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003538static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003539 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003540 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003541{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003542 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003543
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003544 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003545 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003546 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003547 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003548 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003549 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003550 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003551 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003552 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003553 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003554 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003555 if (!isalnum(ch) && ch != '_')
3556 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003557 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003558 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003559 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003560 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003561 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003562 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003563 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003564 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003565 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003566 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003567 o_addchr(dest, ch | quote_mask);
3568 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003569 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003570 case '$': /* pid */
3571 case '!': /* last bg pid */
3572 case '?': /* last exit code */
3573 case '#': /* number of args */
3574 case '*': /* args */
3575 case '@': /* args */
3576 goto make_one_char_var;
3577 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003578 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3579
Denys Vlasenko74369502010-05-21 19:52:01 +02003580 ch = i_getch(input); /* eat '{' */
3581 nommu_addchr(as_string, ch);
3582
3583 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003584 /* It should be ${?}, or ${#var},
3585 * or even ${?+subst} - operator acting on a special variable,
3586 * or the beginning of variable name.
3587 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003588 if (ch == EOF
3589 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3590 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003591 bad_dollar_syntax:
3592 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003593 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003594 return 1;
3595 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003596 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003597 ch |= quote_mask;
3598
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003599 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003600 * However, this regresses some of our testsuite cases
3601 * which check invalid constructs like ${%}.
3602 * Oh well... let's check that the var name part is fine... */
3603
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003604 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003605 unsigned pos;
3606
Denys Vlasenko74369502010-05-21 19:52:01 +02003607 o_addchr(dest, ch);
3608 debug_printf_parse(": '%c'\n", ch);
3609
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003610 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003611 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003612 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003613 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003614
Denys Vlasenko74369502010-05-21 19:52:01 +02003615 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003616 unsigned end_ch;
3617 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003618 /* handle parameter expansions
3619 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3620 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003621 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003622 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003623
3624 /* Eat everything until closing '}' (or ':') */
3625 end_ch = '}';
3626 if (ENABLE_HUSH_BASH_COMPAT
3627 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003628 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003629 ) {
3630 /* It's ${var:N[:M]} thing */
3631 end_ch = '}' * 0x100 + ':';
3632 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003633 if (ENABLE_HUSH_BASH_COMPAT
3634 && ch == '/'
3635 ) {
3636 /* It's ${var/[/]pattern[/repl]} thing */
3637 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3638 i_getch(input);
3639 nommu_addchr(as_string, '/');
3640 ch = '\\';
3641 }
3642 end_ch = '}' * 0x100 + '/';
3643 }
3644 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003645 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003646 if (!BB_MMU)
3647 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003648#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003649 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003650#else
3651#error Simple code to only allow ${var} is not implemented
3652#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003653 if (as_string) {
3654 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003655 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003656 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003657
3658 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3659 /* close the first block: */
3660 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003661 /* while parsing N from ${var:N[:M]}
3662 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003663 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003664 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003665 end_ch = '}';
3666 goto again;
3667 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003668 /* got '}' */
3669 if (end_ch == '}' * 0x100 + ':') {
3670 /* it's ${var:N} - emulate :999999999 */
3671 o_addstr(dest, "999999999");
3672 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003673 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003674 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003675 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003676 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003677 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3678 break;
3679 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003680#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003681 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003682 unsigned pos;
3683
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003684 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003685 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003686# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003687 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003688 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003689 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003690 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3691 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003692 if (!BB_MMU)
3693 pos = dest->length;
3694 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003695 if (as_string) {
3696 o_addstr(as_string, dest->data + pos);
3697 o_addchr(as_string, ')');
3698 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003699 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003701 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003702 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003703# endif
3704# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3706 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003707 if (!BB_MMU)
3708 pos = dest->length;
3709 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003710 if (as_string) {
3711 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003712 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003713 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003714 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003715# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003716 break;
3717 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003718#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003719 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003720 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003721 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003722 ch = i_peek(input);
3723 if (isalnum(ch)) { /* it's $_name or $_123 */
3724 ch = '_';
3725 goto make_var;
3726 }
3727 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003728 /* TODO: $_ and $-: */
3729 /* $_ Shell or shell script name; or last argument of last command
3730 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3731 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003732 /* $- Option flags set by set builtin or shell options (-i etc) */
3733 default:
3734 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003735 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003736 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003737 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003738#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003739}
3740
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003741#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003742# if ENABLE_HUSH_BASH_COMPAT
3743#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3744 encode_string(dest, input, dquote_end, process_bkslash)
3745# else
3746/* only ${var/pattern/repl} (its pattern part) needs additional mode */
3747#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3748 encode_string(dest, input, dquote_end)
3749# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003750#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003751
3752#else /* !MMU */
3753
3754# if ENABLE_HUSH_BASH_COMPAT
3755/* all parameters are needed, no macro tricks */
3756# else
3757#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3758 encode_string(as_string, dest, input, dquote_end)
3759# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003760#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003761static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003762 o_string *dest,
3763 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02003764 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003765 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003766{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003767#if !ENABLE_HUSH_BASH_COMPAT
3768 const int process_bkslash = 1;
3769#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003770 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003771 int next;
3772
3773 again:
3774 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003775 if (ch != EOF)
3776 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003777 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003778 debug_printf_parse("encode_string return 0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003779 return 0;
3780 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003781 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003782 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003783 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003784 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003785 }
3786 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003787 if (ch != '\n') {
3788 next = i_peek(input);
3789 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003790 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003791 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003792 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003793 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003794 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003795 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003796 }
3797 /* bash:
3798 * "The backslash retains its special meaning [in "..."]
3799 * only when followed by one of the following characters:
3800 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003801 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003802 * NB: in (unquoted) heredoc, above does not apply to ",
3803 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003804 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003805 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003806 ch = i_getch(input); /* eat next */
3807 if (ch == '\n')
3808 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02003809 } /* else: ch remains == '\\', and we double it below: */
3810 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003811 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003812 goto again;
3813 }
3814 if (ch == '$') {
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003815 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003816 debug_printf_parse("encode_string return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003817 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003818 return 1;
3819 }
3820 goto again;
3821 }
3822#if ENABLE_HUSH_TICK
3823 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003824 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003825 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3826 o_addchr(dest, 0x80 | '`');
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003827 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003828 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3829 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003830 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003831 }
3832#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003833 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003834 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003835#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003836}
3837
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003838/*
3839 * Scan input until EOF or end_trigger char.
3840 * Return a list of pipes to execute, or NULL on EOF
3841 * or if end_trigger character is met.
3842 * On syntax error, exit is shell is not interactive,
3843 * reset parsing machinery and start parsing anew,
3844 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003845 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003846static struct pipe *parse_stream(char **pstring,
3847 struct in_str *input,
3848 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003849{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003850 struct parse_context ctx;
3851 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003852 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00003853
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003854 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003855 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003856 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003857 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02003858 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003859 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003860
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003861 /* If very first arg is "" or '', dest.data may end up NULL.
3862 * Preventing this: */
3863 o_addchr(&dest, '\0');
3864 dest.length = 0;
3865
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003866 /* We used to separate words on $IFS here. This was wrong.
3867 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003868 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003869 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003870
3871 reset: /* we come back here only on syntax errors in interactive shell */
3872
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003873#if ENABLE_HUSH_INTERACTIVE
3874 input->promptmode = 0; /* PS1 */
3875#endif
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003876 if (MAYBE_ASSIGNMENT != 0)
3877 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003878 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003879 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003880 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003881 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003882 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003883 int ch;
3884 int next;
3885 int redir_fd;
3886 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003887
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003888 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003889 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003890 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003891 if (ch == EOF) {
3892 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003893
3894 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003895 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003896 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003897 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003898 /* end_trigger == '}' case errors out earlier,
3899 * checking only ')' */
3900 if (end_trigger == ')') {
3901 syntax_error_unterm_ch('('); /* exits */
3902 /* goto parse_error; */
3903 }
3904
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003905 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003906 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003907 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003908 o_free(&dest);
3909 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003910 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003911 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003912 /* (this makes bare "&" cmd a no-op.
3913 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003914 if (pi->num_cmds == 0
3915 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3916 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003917 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003918 pi = NULL;
3919 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003920#if !BB_MMU
3921 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3922 if (pstring)
3923 *pstring = ctx.as_string.data;
3924 else
3925 o_free_unsafe(&ctx.as_string);
3926#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003927 debug_leave();
3928 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003929 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003930 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003931 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003932
3933 next = '\0';
3934 if (ch != '\n')
3935 next = i_peek(input);
3936
3937 is_special = "{}<>;&|()#'" /* special outside of "str" */
3938 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3939 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003940 if (ctx.command->argv /* word [word]{... - non-special */
3941 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003942 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003943 || (next != ';' /* }; - special */
3944 && next != ')' /* }) - special */
3945 && next != '&' /* }& and }&& ... - special */
3946 && next != '|' /* }|| ... - special */
3947 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003948 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003949 ) {
3950 /* They are not special, skip "{}" */
3951 is_special += 2;
3952 }
3953 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003954 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003955
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003956 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003957 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003958 o_addQchr(&dest, ch);
3959 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3960 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003961 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003962 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00003963 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003964 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003965 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003966 continue;
3967 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00003968
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003969 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003970 if (done_word(&dest, &ctx)) {
3971 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00003972 }
Denis Vlasenko37181682009-04-03 03:19:15 +00003973 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003974#if ENABLE_HUSH_CASE
3975 /* "case ... in <newline> word) ..." -
3976 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003977 if (ctx.command->argv == NULL
3978 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00003979 ) {
3980 continue;
3981 }
3982#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003983 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003984 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003985 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3986 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003987 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003988 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003989 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003990 heredoc_cnt = 0;
3991 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003992 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003993 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003994 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003995 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003996 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003997 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00003998
3999 /* "cmd}" or "cmd }..." without semicolon or &:
4000 * } is an ordinary char in this case, even inside { cmd; }
4001 * Pathological example: { ""}; } should exec "}" cmd
4002 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004003 if (ch == '}') {
4004 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4005 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004006 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004007 ) {
4008 goto ordinary_char;
4009 }
4010 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4011 goto skip_end_trigger;
4012 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004013 }
4014
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004015 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004016 && (ch != ';' || heredoc_cnt == 0)
4017#if ENABLE_HUSH_CASE
4018 && (ch != ')'
4019 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004020 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004021 )
4022#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004023 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004024 if (heredoc_cnt) {
4025 /* This is technically valid:
4026 * { cat <<HERE; }; echo Ok
4027 * heredoc
4028 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004029 * HERE
4030 * but we don't support this.
4031 * We require heredoc to be in enclosing {}/(),
4032 * if any.
4033 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004034 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004035 goto parse_error;
4036 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004037 if (done_word(&dest, &ctx)) {
4038 goto parse_error;
4039 }
4040 done_pipe(&ctx, PIPE_SEQ);
4041 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004042 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004043 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004044 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004045 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004046 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004047#if !BB_MMU
4048 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4049 if (pstring)
4050 *pstring = ctx.as_string.data;
4051 else
4052 o_free_unsafe(&ctx.as_string);
4053#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004054 debug_leave();
4055 debug_printf_parse("parse_stream return %p: "
4056 "end_trigger char found\n",
4057 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004058 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004059 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004060 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004061 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004062 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004063 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004064
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004065 /* Catch <, > before deciding whether this word is
4066 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4067 switch (ch) {
4068 case '>':
4069 redir_fd = redirect_opt_num(&dest);
4070 if (done_word(&dest, &ctx)) {
4071 goto parse_error;
4072 }
4073 redir_style = REDIRECT_OVERWRITE;
4074 if (next == '>') {
4075 redir_style = REDIRECT_APPEND;
4076 ch = i_getch(input);
4077 nommu_addchr(&ctx.as_string, ch);
4078 }
4079#if 0
4080 else if (next == '(') {
4081 syntax_error(">(process) not supported");
4082 goto parse_error;
4083 }
4084#endif
4085 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4086 goto parse_error;
4087 continue; /* back to top of while (1) */
4088 case '<':
4089 redir_fd = redirect_opt_num(&dest);
4090 if (done_word(&dest, &ctx)) {
4091 goto parse_error;
4092 }
4093 redir_style = REDIRECT_INPUT;
4094 if (next == '<') {
4095 redir_style = REDIRECT_HEREDOC;
4096 heredoc_cnt++;
4097 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4098 ch = i_getch(input);
4099 nommu_addchr(&ctx.as_string, ch);
4100 } else if (next == '>') {
4101 redir_style = REDIRECT_IO;
4102 ch = i_getch(input);
4103 nommu_addchr(&ctx.as_string, ch);
4104 }
4105#if 0
4106 else if (next == '(') {
4107 syntax_error("<(process) not supported");
4108 goto parse_error;
4109 }
4110#endif
4111 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4112 goto parse_error;
4113 continue; /* back to top of while (1) */
4114 }
4115
4116 if (dest.o_assignment == MAYBE_ASSIGNMENT
4117 /* check that we are not in word in "a=1 2>word b=1": */
4118 && !ctx.pending_redirect
4119 ) {
4120 /* ch is a special char and thus this word
4121 * cannot be an assignment */
4122 dest.o_assignment = NOT_ASSIGNMENT;
4123 }
4124
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004125 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4126
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004127 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00004128 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004129 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004130 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004131 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004132 if (ch == EOF || ch == '\n')
4133 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004134 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004135 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004136 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004137 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00004138 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004139 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004140 }
4141 break;
4142 case '\\':
4143 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004144 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004145 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004146 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004147 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004148 if (ch != '\n') {
4149 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004150 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004151 o_addchr(&dest, ch);
4152 nommu_addchr(&ctx.as_string, ch);
4153 /* Example: echo Hello \2>file
4154 * we need to know that word 2 is quoted */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004155 dest.has_quoted_part = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004156 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004157#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004158 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004159 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4160 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004161 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02004162#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004163 break;
4164 case '$':
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004165 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004166 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004167 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004168 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004169 }
Eric Andersen25f27032001-04-26 23:22:31 +00004170 break;
4171 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004172 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004173 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004174 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004175 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004176 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004177 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004178 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004179 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004180 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004181 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004182 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004183 }
Eric Andersen25f27032001-04-26 23:22:31 +00004184 break;
4185 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004186 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004187 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004188 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004189 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004190 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004191 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004192 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004193#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004194 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004195 unsigned pos;
4196
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004197 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4198 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004199 pos = dest.length;
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004200 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004201# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004202 o_addstr(&ctx.as_string, dest.data + pos);
4203 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004204# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004205 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4206 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004207 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004208 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004209#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004210 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004211#if ENABLE_HUSH_CASE
4212 case_semi:
4213#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004214 if (done_word(&dest, &ctx)) {
4215 goto parse_error;
4216 }
4217 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004218#if ENABLE_HUSH_CASE
4219 /* Eat multiple semicolons, detect
4220 * whether it means something special */
4221 while (1) {
4222 ch = i_peek(input);
4223 if (ch != ';')
4224 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004225 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004226 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004227 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004228 ctx.ctx_dsemicolon = 1;
4229 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004230 break;
4231 }
4232 }
4233#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004234 new_cmd:
4235 /* We just finished a cmd. New one may start
4236 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004237 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004238 break;
4239 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004240 if (done_word(&dest, &ctx)) {
4241 goto parse_error;
4242 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004243 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004244 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004245 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004246 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004247 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004248 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004249 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004250 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004251 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004252 if (done_word(&dest, &ctx)) {
4253 goto parse_error;
4254 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004255#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004256 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004257 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004258#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004259 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004260 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004261 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004262 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004263 } else {
4264 /* we could pick up a file descriptor choice here
4265 * with redirect_opt_num(), but bash doesn't do it.
4266 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004267 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004268#if !BB_MMU
4269 o_reset_to_empty_unquoted(&ctx.as_string);
4270#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004271 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004272 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004273 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004274#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004275 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004276 if (ctx.ctx_res_w == RES_MATCH
4277 && ctx.command->argv == NULL /* not (word|(... */
4278 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004279 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004280 ) {
4281 continue;
4282 }
4283#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004284 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004285 if (parse_group(&dest, &ctx, input, ch) != 0) {
4286 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004287 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004288 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004289 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004290#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004291 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004292 goto case_semi;
4293#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004294 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004295 /* proper use of this character is caught by end_trigger:
4296 * if we see {, we call parse_group(..., end_trigger='}')
4297 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004298 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004299 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004300 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004301 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004302 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004303 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004304 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004305
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004306 parse_error:
4307 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004308 struct parse_context *pctx;
4309 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004310
4311 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004312 * Sample for finding leaks on syntax error recovery path.
4313 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004314 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004315 * Samples to catch leaks at execution:
4316 * while if (true | {true;}); then echo ok; fi; do break; done
4317 * 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 +00004318 */
4319 pctx = &ctx;
4320 do {
4321 /* Update pipe/command counts,
4322 * otherwise freeing may miss some */
4323 done_pipe(pctx, PIPE_SEQ);
4324 debug_printf_clean("freeing list %p from ctx %p\n",
4325 pctx->list_head, pctx);
4326 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004327 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004328 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004329#if !BB_MMU
4330 o_free_unsafe(&pctx->as_string);
4331#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004332 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004333 if (pctx != &ctx) {
4334 free(pctx);
4335 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004336 IF_HAS_KEYWORDS(pctx = p2;)
4337 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004338 /* Free text, clear all dest fields */
4339 o_free(&dest);
4340 /* If we are not in top-level parse, we return,
4341 * our caller will propagate error.
4342 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004343 if (end_trigger != ';') {
4344#if !BB_MMU
4345 if (pstring)
4346 *pstring = NULL;
4347#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004348 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004349 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004350 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004351 /* Discard cached input, force prompt */
4352 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004353 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004354 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004355 }
Eric Andersen25f27032001-04-26 23:22:31 +00004356}
4357
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004358
4359/*** Execution routines ***/
4360
4361/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004362#if !ENABLE_HUSH_BASH_COMPAT
4363/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4364#define expand_string_to_string(str, do_unbackslash) \
4365 expand_string_to_string(str)
4366#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004367static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004368static int process_command_subs(o_string *dest, const char *s);
4369
4370/* expand_strvec_to_strvec() takes a list of strings, expands
4371 * all variable references within and returns a pointer to
4372 * a list of expanded strings, possibly with larger number
4373 * of strings. (Think VAR="a b"; echo $VAR).
4374 * This new list is allocated as a single malloc block.
4375 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004376 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004377 * Caller can deallocate entire list by single free(list). */
4378
Denys Vlasenko238081f2010-10-03 14:26:26 +02004379/* A horde of its helpers come first: */
4380
4381static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4382{
4383 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004384 char c = *str++;
4385#if ENABLE_HUSH_BRACE_EXPANSION
4386 if (c == '{' || c == '}') {
4387 /* { -> \{, } -> \} */
4388 o_addchr(o, '\\');
4389 o_addchr(o, c);
4390 continue;
4391 }
4392#endif
4393 o_addchr(o, c);
4394 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004395 /* \z -> \\\z; \<eol> -> \\<eol> */
4396 o_addchr(o, '\\');
4397 if (len) {
4398 len--;
4399 o_addchr(o, '\\');
4400 o_addchr(o, *str++);
4401 }
4402 }
4403 }
4404}
4405
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004406/* Store given string, finalizing the word and starting new one whenever
4407 * we encounter IFS char(s). This is used for expanding variable values.
4408 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4409static int expand_on_ifs(o_string *output, int n, const char *str)
4410{
4411 while (1) {
4412 int word_len = strcspn(str, G.ifs);
4413 if (word_len) {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004414 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004415 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004416 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004417 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004418 * Example: "v='\*'; echo b$v" prints "b\*"
4419 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004420 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004421 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004422 /*/ Why can't we do it easier? */
4423 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4424 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4425 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004426 str += word_len;
4427 }
4428 if (!*str) /* EOL - do not finalize word */
4429 break;
4430 o_addchr(output, '\0');
4431 debug_print_list("expand_on_ifs", output, n);
4432 n = o_save_ptr(output, n);
4433 str += strspn(str, G.ifs); /* skip ifs chars */
4434 }
4435 debug_print_list("expand_on_ifs[1]", output, n);
4436 return n;
4437}
4438
4439/* Helper to expand $((...)) and heredoc body. These act as if
4440 * they are in double quotes, with the exception that they are not :).
4441 * Just the rules are similar: "expand only $var and `cmd`"
4442 *
4443 * Returns malloced string.
4444 * As an optimization, we return NULL if expansion is not needed.
4445 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004446#if !ENABLE_HUSH_BASH_COMPAT
4447/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4448#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4449 encode_then_expand_string(str)
4450#endif
4451static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004452{
4453 char *exp_str;
4454 struct in_str input;
4455 o_string dest = NULL_O_STRING;
4456
4457 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004458 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004459#if ENABLE_HUSH_TICK
4460 && !strchr(str, '`')
4461#endif
4462 ) {
4463 return NULL;
4464 }
4465
4466 /* We need to expand. Example:
4467 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4468 */
4469 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004470 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004471 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004472 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004473 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4474 o_free_unsafe(&dest);
4475 return exp_str;
4476}
4477
4478#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004479static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004480{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004481 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004482 arith_t res;
4483 char *exp_str;
4484
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004485 math_state.lookupvar = get_local_var_value;
4486 math_state.setvar = set_local_var_from_halves;
4487 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004488 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004489 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004490 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004491 if (errmsg_p)
4492 *errmsg_p = math_state.errmsg;
4493 if (math_state.errmsg)
4494 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004495 return res;
4496}
4497#endif
4498
4499#if ENABLE_HUSH_BASH_COMPAT
4500/* ${var/[/]pattern[/repl]} helpers */
4501static char *strstr_pattern(char *val, const char *pattern, int *size)
4502{
4503 while (1) {
4504 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4505 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4506 if (end) {
4507 *size = end - val;
4508 return val;
4509 }
4510 if (*val == '\0')
4511 return NULL;
4512 /* Optimization: if "*pat" did not match the start of "string",
4513 * we know that "tring", "ring" etc will not match too:
4514 */
4515 if (pattern[0] == '*')
4516 return NULL;
4517 val++;
4518 }
4519}
4520static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4521{
4522 char *result = NULL;
4523 unsigned res_len = 0;
4524 unsigned repl_len = strlen(repl);
4525
4526 while (1) {
4527 int size;
4528 char *s = strstr_pattern(val, pattern, &size);
4529 if (!s)
4530 break;
4531
4532 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4533 memcpy(result + res_len, val, s - val);
4534 res_len += s - val;
4535 strcpy(result + res_len, repl);
4536 res_len += repl_len;
4537 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4538
4539 val = s + size;
4540 if (exp_op == '/')
4541 break;
4542 }
4543 if (val[0] && result) {
4544 result = xrealloc(result, res_len + strlen(val) + 1);
4545 strcpy(result + res_len, val);
4546 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4547 }
4548 debug_printf_varexp("result:'%s'\n", result);
4549 return result;
4550}
4551#endif
4552
4553/* Helper:
4554 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4555 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004556static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004557{
4558 const char *val = NULL;
4559 char *to_be_freed = NULL;
4560 char *p = *pp;
4561 char *var;
4562 char first_char;
4563 char exp_op;
4564 char exp_save = exp_save; /* for compiler */
4565 char *exp_saveptr; /* points to expansion operator */
4566 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004567 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004568
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004569 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004570 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004571 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004572 arg0 = arg[0];
4573 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004574 exp_op = 0;
4575
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004576 if (first_char == '#' /* ${#... */
4577 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4578 ) {
4579 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004580 var++;
4581 exp_op = 'L';
4582 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004583 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004584 if (exp_saveptr /* if 2nd char is one of expansion operators */
4585 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4586 ) {
4587 /* ${?:0}, ${#[:]%0} etc */
4588 exp_saveptr = var + 1;
4589 } else {
4590 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4591 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4592 }
4593 exp_op = exp_save = *exp_saveptr;
4594 if (exp_op) {
4595 exp_word = exp_saveptr + 1;
4596 if (exp_op == ':') {
4597 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004598//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004599 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004600 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004601 ) {
4602 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4603 exp_op = ':';
4604 exp_word--;
4605 }
4606 }
4607 *exp_saveptr = '\0';
4608 } /* else: it's not an expansion op, but bare ${var} */
4609 }
4610
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004611 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004612 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004613 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004614 int n = xatoi_positive(var);
4615 if (n < G.global_argc)
4616 val = G.global_argv[n];
4617 /* else val remains NULL: $N with too big N */
4618 } else {
4619 switch (var[0]) {
4620 case '$': /* pid */
4621 val = utoa(G.root_pid);
4622 break;
4623 case '!': /* bg pid */
4624 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4625 break;
4626 case '?': /* exitcode */
4627 val = utoa(G.last_exitcode);
4628 break;
4629 case '#': /* argc */
4630 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4631 break;
4632 default:
4633 val = get_local_var_value(var);
4634 }
4635 }
4636
4637 /* Handle any expansions */
4638 if (exp_op == 'L') {
4639 debug_printf_expand("expand: length(%s)=", val);
4640 val = utoa(val ? strlen(val) : 0);
4641 debug_printf_expand("%s\n", val);
4642 } else if (exp_op) {
4643 if (exp_op == '%' || exp_op == '#') {
4644 /* Standard-mandated substring removal ops:
4645 * ${parameter%word} - remove smallest suffix pattern
4646 * ${parameter%%word} - remove largest suffix pattern
4647 * ${parameter#word} - remove smallest prefix pattern
4648 * ${parameter##word} - remove largest prefix pattern
4649 *
4650 * Word is expanded to produce a glob pattern.
4651 * Then var's value is matched to it and matching part removed.
4652 */
4653 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004654 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004655 char *exp_exp_word;
4656 char *loc;
4657 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4658 if (exp_op == *exp_word) /* ## or %% */
4659 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004660 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004661 if (exp_exp_word)
4662 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004663 /* HACK ALERT. We depend here on the fact that
4664 * G.global_argv and results of utoa and get_local_var_value
4665 * are actually in writable memory:
4666 * scan_and_match momentarily stores NULs there. */
4667 t = (char*)val;
4668 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004669 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004670 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004671 free(exp_exp_word);
4672 if (loc) { /* match was found */
4673 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004674 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004675 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004676 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004677 }
4678 }
4679 }
4680#if ENABLE_HUSH_BASH_COMPAT
4681 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004682 /* It's ${var/[/]pattern[/repl]} thing.
4683 * Note that in encoded form it has TWO parts:
4684 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02004685 * and if // is used, it is encoded as \:
4686 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004687 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004688 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004689 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004690 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004691 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004692 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004693 * by the usual expansion rules:
4694 * >az; >bz;
4695 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4696 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4697 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4698 * v='a bz'; echo ${v/a*z/\z} prints "z"
4699 * (note that a*z _pattern_ is never globbed!)
4700 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004701 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004702 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004703 if (!pattern)
4704 pattern = xstrdup(exp_word);
4705 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4706 *p++ = SPECIAL_VAR_SYMBOL;
4707 exp_word = p;
4708 p = strchr(p, SPECIAL_VAR_SYMBOL);
4709 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004710 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004711 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4712 /* HACK ALERT. We depend here on the fact that
4713 * G.global_argv and results of utoa and get_local_var_value
4714 * are actually in writable memory:
4715 * replace_pattern momentarily stores NULs there. */
4716 t = (char*)val;
4717 to_be_freed = replace_pattern(t,
4718 pattern,
4719 (repl ? repl : exp_word),
4720 exp_op);
4721 if (to_be_freed) /* at least one replace happened */
4722 val = to_be_freed;
4723 free(pattern);
4724 free(repl);
4725 }
4726 }
4727#endif
4728 else if (exp_op == ':') {
4729#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4730 /* It's ${var:N[:M]} bashism.
4731 * Note that in encoded form it has TWO parts:
4732 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4733 */
4734 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02004735 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004736
Denys Vlasenko063847d2010-09-15 13:33:02 +02004737 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4738 if (errmsg)
4739 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004740 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4741 *p++ = SPECIAL_VAR_SYMBOL;
4742 exp_word = p;
4743 p = strchr(p, SPECIAL_VAR_SYMBOL);
4744 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02004745 len = expand_and_evaluate_arith(exp_word, &errmsg);
4746 if (errmsg)
4747 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004748 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004749 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004750 if (beg < 0) /* bash compat */
4751 beg = 0;
4752 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004753 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02004754 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02004755 val = NULL;
4756 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004757 /* Paranoia. What if user entered 9999999999999
4758 * which fits in arith_t but not int? */
4759 if (len >= INT_MAX)
4760 len = INT_MAX;
4761 val = to_be_freed = xstrndup(val + beg, len);
4762 }
4763 debug_printf_varexp("val:'%s'\n", val);
4764 } else
4765#endif
4766 {
4767 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004768 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004769 }
4770 } else { /* one of "-=+?" */
4771 /* Standard-mandated substitution ops:
4772 * ${var?word} - indicate error if unset
4773 * If var is unset, word (or a message indicating it is unset
4774 * if word is null) is written to standard error
4775 * and the shell exits with a non-zero exit status.
4776 * Otherwise, the value of var is substituted.
4777 * ${var-word} - use default value
4778 * If var is unset, word is substituted.
4779 * ${var=word} - assign and use default value
4780 * If var is unset, word is assigned to var.
4781 * In all cases, final value of var is substituted.
4782 * ${var+word} - use alternative value
4783 * If var is unset, null is substituted.
4784 * Otherwise, word is substituted.
4785 *
4786 * Word is subjected to tilde expansion, parameter expansion,
4787 * command substitution, and arithmetic expansion.
4788 * If word is not needed, it is not expanded.
4789 *
4790 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4791 * but also treat null var as if it is unset.
4792 */
4793 int use_word = (!val || ((exp_save == ':') && !val[0]));
4794 if (exp_op == '+')
4795 use_word = !use_word;
4796 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4797 (exp_save == ':') ? "true" : "false", use_word);
4798 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004799 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004800 if (to_be_freed)
4801 exp_word = to_be_freed;
4802 if (exp_op == '?') {
4803 /* mimic bash message */
4804 die_if_script("%s: %s",
4805 var,
4806 exp_word[0] ? exp_word : "parameter null or not set"
4807 );
4808//TODO: how interactive bash aborts expansion mid-command?
4809 } else {
4810 val = exp_word;
4811 }
4812
4813 if (exp_op == '=') {
4814 /* ${var=[word]} or ${var:=[word]} */
4815 if (isdigit(var[0]) || var[0] == '#') {
4816 /* mimic bash message */
4817 die_if_script("$%s: cannot assign in this way", var);
4818 val = NULL;
4819 } else {
4820 char *new_var = xasprintf("%s=%s", var, val);
4821 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4822 }
4823 }
4824 }
4825 } /* one of "-=+?" */
4826
4827 *exp_saveptr = exp_save;
4828 } /* if (exp_op) */
4829
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004830 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004831
4832 *pp = p;
4833 *to_be_freed_pp = to_be_freed;
4834 return val;
4835}
4836
4837/* Expand all variable references in given string, adding words to list[]
4838 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4839 * to be filled). This routine is extremely tricky: has to deal with
4840 * variables/parameters with whitespace, $* and $@, and constructs like
4841 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004842static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004843{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004844 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004845 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004846 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004847 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004848 char *p;
4849
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004850 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4851 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004852 debug_print_list("expand_vars_to_list", output, n);
4853 n = o_save_ptr(output, n);
4854 debug_print_list("expand_vars_to_list[0]", output, n);
4855
4856 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4857 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004858 char *to_be_freed = NULL;
4859 const char *val = NULL;
4860#if ENABLE_HUSH_TICK
4861 o_string subst_result = NULL_O_STRING;
4862#endif
4863#if ENABLE_SH_MATH_SUPPORT
4864 char arith_buf[sizeof(arith_t)*3 + 2];
4865#endif
4866 o_addblock(output, arg, p - arg);
4867 debug_print_list("expand_vars_to_list[1]", output, n);
4868 arg = ++p;
4869 p = strchr(p, SPECIAL_VAR_SYMBOL);
4870
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004871 /* Fetch special var name (if it is indeed one of them)
4872 * and quote bit, force the bit on if singleword expansion -
4873 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004874 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004875
4876 /* Is this variable quoted and thus expansion can't be null?
4877 * "$@" is special. Even if quoted, it can still
4878 * expand to nothing (not even an empty string),
4879 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004880 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004881 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004882
4883 switch (first_ch & 0x7f) {
4884 /* Highest bit in first_ch indicates that var is double-quoted */
4885 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004886 case '@': {
4887 int i;
4888 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004889 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004890 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004891 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004892 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004893 while (G.global_argv[i]) {
4894 n = expand_on_ifs(output, n, G.global_argv[i]);
4895 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4896 if (G.global_argv[i++][0] && G.global_argv[i]) {
4897 /* this argv[] is not empty and not last:
4898 * put terminating NUL, start new word */
4899 o_addchr(output, '\0');
4900 debug_print_list("expand_vars_to_list[2]", output, n);
4901 n = o_save_ptr(output, n);
4902 debug_print_list("expand_vars_to_list[3]", output, n);
4903 }
4904 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004905 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004906 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004907 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004908 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004909 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004910 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004911 while (1) {
4912 o_addQstr(output, G.global_argv[i]);
4913 if (++i >= G.global_argc)
4914 break;
4915 o_addchr(output, '\0');
4916 debug_print_list("expand_vars_to_list[4]", output, n);
4917 n = o_save_ptr(output, n);
4918 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004919 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004920 while (1) {
4921 o_addQstr(output, G.global_argv[i]);
4922 if (!G.global_argv[++i])
4923 break;
4924 if (G.ifs[0])
4925 o_addchr(output, G.ifs[0]);
4926 }
4927 }
4928 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004929 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004930 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4931 /* "Empty variable", used to make "" etc to not disappear */
4932 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004933 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004934 break;
4935#if ENABLE_HUSH_TICK
4936 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004937 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004938 arg++;
4939 /* Can't just stuff it into output o_string,
4940 * expanded result may need to be globbed
4941 * and $IFS-splitted */
4942 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4943 G.last_exitcode = process_command_subs(&subst_result, arg);
4944 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4945 val = subst_result.data;
4946 goto store_val;
4947#endif
4948#if ENABLE_SH_MATH_SUPPORT
4949 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4950 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004951
4952 arg++; /* skip '+' */
4953 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4954 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004955 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02004956 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
4957 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004958 val = arith_buf;
4959 break;
4960 }
4961#endif
4962 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004963 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004964 IF_HUSH_TICK(store_val:)
4965 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004966 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
4967 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004968 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004969 n = expand_on_ifs(output, n, val);
4970 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004971 }
4972 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004973 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
4974 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004975 }
4976 break;
4977
4978 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4979
4980 if (val && val[0]) {
4981 o_addQstr(output, val);
4982 }
4983 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004984
4985 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
4986 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004987 if (*p != SPECIAL_VAR_SYMBOL)
4988 *p = SPECIAL_VAR_SYMBOL;
4989
4990#if ENABLE_HUSH_TICK
4991 o_free(&subst_result);
4992#endif
4993 arg = ++p;
4994 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4995
4996 if (arg[0]) {
4997 debug_print_list("expand_vars_to_list[a]", output, n);
4998 /* this part is literal, and it was already pre-quoted
4999 * if needed (much earlier), do not use o_addQstr here! */
5000 o_addstr_with_NUL(output, arg);
5001 debug_print_list("expand_vars_to_list[b]", output, n);
5002 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005003 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005004 ) {
5005 n--;
5006 /* allow to reuse list[n] later without re-growth */
5007 output->has_empty_slot = 1;
5008 } else {
5009 o_addchr(output, '\0');
5010 }
5011
5012 return n;
5013}
5014
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005015static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005016{
5017 int n;
5018 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005019 o_string output = NULL_O_STRING;
5020
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005021 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005022
5023 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005024 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005025 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005026 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005027 }
5028 debug_print_list("expand_variables", &output, n);
5029
5030 /* output.data (malloced in one block) gets returned in "list" */
5031 list = o_finalize_list(&output, n);
5032 debug_print_strings("expand_variables[1]", list);
5033 return list;
5034}
5035
5036static char **expand_strvec_to_strvec(char **argv)
5037{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005038 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005039}
5040
5041#if ENABLE_HUSH_BASH_COMPAT
5042static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5043{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005044 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005045}
5046#endif
5047
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005048/* Used for expansion of right hand of assignments,
5049 * $((...)), heredocs, variable espansion parts.
5050 *
5051 * NB: should NOT do globbing!
5052 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5053 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005054static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005055{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005056#if !ENABLE_HUSH_BASH_COMPAT
5057 const int do_unbackslash = 1;
5058#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005059 char *argv[2], **list;
5060
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005061 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005062 /* This is generally an optimization, but it also
5063 * handles "", which otherwise trips over !list[0] check below.
5064 * (is this ever happens that we actually get str="" here?)
5065 */
5066 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5067 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005068 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005069 return xstrdup(str);
5070 }
5071
5072 argv[0] = (char*)str;
5073 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005074 list = expand_variables(argv, do_unbackslash
5075 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5076 : EXP_FLAG_SINGLEWORD
5077 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005078 if (HUSH_DEBUG)
5079 if (!list[0] || list[1])
5080 bb_error_msg_and_die("BUG in varexp2");
5081 /* actually, just move string 2*sizeof(char*) bytes back */
5082 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005083 if (do_unbackslash)
5084 unbackslash((char*)list);
5085 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005086 return (char*)list;
5087}
5088
5089/* Used for "eval" builtin */
5090static char* expand_strvec_to_string(char **argv)
5091{
5092 char **list;
5093
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005094 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005095 /* Convert all NULs to spaces */
5096 if (list[0]) {
5097 int n = 1;
5098 while (list[n]) {
5099 if (HUSH_DEBUG)
5100 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5101 bb_error_msg_and_die("BUG in varexp3");
5102 /* bash uses ' ' regardless of $IFS contents */
5103 list[n][-1] = ' ';
5104 n++;
5105 }
5106 }
5107 overlapping_strcpy((char*)list, list[0]);
5108 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5109 return (char*)list;
5110}
5111
5112static char **expand_assignments(char **argv, int count)
5113{
5114 int i;
5115 char **p;
5116
5117 G.expanded_assignments = p = NULL;
5118 /* Expand assignments into one string each */
5119 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005120 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005121 }
5122 G.expanded_assignments = NULL;
5123 return p;
5124}
5125
5126
5127#if BB_MMU
5128/* never called */
5129void re_execute_shell(char ***to_free, const char *s,
5130 char *g_argv0, char **g_argv,
5131 char **builtin_argv) NORETURN;
5132
5133static void reset_traps_to_defaults(void)
5134{
5135 /* This function is always called in a child shell
5136 * after fork (not vfork, NOMMU doesn't use this function).
5137 */
5138 unsigned sig;
5139 unsigned mask;
5140
5141 /* Child shells are not interactive.
5142 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5143 * Testcase: (while :; do :; done) + ^Z should background.
5144 * Same goes for SIGTERM, SIGHUP, SIGINT.
5145 */
5146 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5147 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5148
5149 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5150 * Stupid. It can be done with *single* &= op, but we can't use
5151 * the fact that G.blocked_set is implemented as a bitmask
5152 * in libc... */
5153 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5154 sig = 1;
5155 while (1) {
5156 if (mask & 1) {
5157 /* Careful. Only if no trap or trap is not "" */
5158 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5159 sigdelset(&G.blocked_set, sig);
5160 }
5161 mask >>= 1;
5162 if (!mask)
5163 break;
5164 sig++;
5165 }
5166 /* Our homegrown sig mask is saner to work with :) */
5167 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5168
5169 /* Resetting all traps to default except empty ones */
5170 mask = G.non_DFL_mask;
5171 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5172 if (!G.traps[sig] || !G.traps[sig][0])
5173 continue;
5174 free(G.traps[sig]);
5175 G.traps[sig] = NULL;
5176 /* There is no signal for 0 (EXIT) */
5177 if (sig == 0)
5178 continue;
5179 /* There was a trap handler, we just removed it.
5180 * But if sig still has non-DFL handling,
5181 * we should not unblock the sig. */
5182 if (mask & 1)
5183 continue;
5184 sigdelset(&G.blocked_set, sig);
5185 }
5186 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5187}
5188
5189#else /* !BB_MMU */
5190
5191static void re_execute_shell(char ***to_free, const char *s,
5192 char *g_argv0, char **g_argv,
5193 char **builtin_argv) NORETURN;
5194static void re_execute_shell(char ***to_free, const char *s,
5195 char *g_argv0, char **g_argv,
5196 char **builtin_argv)
5197{
5198# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5199 /* delims + 2 * (number of bytes in printed hex numbers) */
5200 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5201 char *heredoc_argv[4];
5202 struct variable *cur;
5203# if ENABLE_HUSH_FUNCTIONS
5204 struct function *funcp;
5205# endif
5206 char **argv, **pp;
5207 unsigned cnt;
5208 unsigned long long empty_trap_mask;
5209
5210 if (!g_argv0) { /* heredoc */
5211 argv = heredoc_argv;
5212 argv[0] = (char *) G.argv0_for_re_execing;
5213 argv[1] = (char *) "-<";
5214 argv[2] = (char *) s;
5215 argv[3] = NULL;
5216 pp = &argv[3]; /* used as pointer to empty environment */
5217 goto do_exec;
5218 }
5219
5220 cnt = 0;
5221 pp = builtin_argv;
5222 if (pp) while (*pp++)
5223 cnt++;
5224
5225 empty_trap_mask = 0;
5226 if (G.traps) {
5227 int sig;
5228 for (sig = 1; sig < NSIG; sig++) {
5229 if (G.traps[sig] && !G.traps[sig][0])
5230 empty_trap_mask |= 1LL << sig;
5231 }
5232 }
5233
5234 sprintf(param_buf, NOMMU_HACK_FMT
5235 , (unsigned) G.root_pid
5236 , (unsigned) G.root_ppid
5237 , (unsigned) G.last_bg_pid
5238 , (unsigned) G.last_exitcode
5239 , cnt
5240 , empty_trap_mask
5241 IF_HUSH_LOOPS(, G.depth_of_loop)
5242 );
5243# undef NOMMU_HACK_FMT
5244 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5245 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5246 */
5247 cnt += 6;
5248 for (cur = G.top_var; cur; cur = cur->next) {
5249 if (!cur->flg_export || cur->flg_read_only)
5250 cnt += 2;
5251 }
5252# if ENABLE_HUSH_FUNCTIONS
5253 for (funcp = G.top_func; funcp; funcp = funcp->next)
5254 cnt += 3;
5255# endif
5256 pp = g_argv;
5257 while (*pp++)
5258 cnt++;
5259 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5260 *pp++ = (char *) G.argv0_for_re_execing;
5261 *pp++ = param_buf;
5262 for (cur = G.top_var; cur; cur = cur->next) {
5263 if (strcmp(cur->varstr, hush_version_str) == 0)
5264 continue;
5265 if (cur->flg_read_only) {
5266 *pp++ = (char *) "-R";
5267 *pp++ = cur->varstr;
5268 } else if (!cur->flg_export) {
5269 *pp++ = (char *) "-V";
5270 *pp++ = cur->varstr;
5271 }
5272 }
5273# if ENABLE_HUSH_FUNCTIONS
5274 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5275 *pp++ = (char *) "-F";
5276 *pp++ = funcp->name;
5277 *pp++ = funcp->body_as_string;
5278 }
5279# endif
5280 /* We can pass activated traps here. Say, -Tnn:trap_string
5281 *
5282 * However, POSIX says that subshells reset signals with traps
5283 * to SIG_DFL.
5284 * I tested bash-3.2 and it not only does that with true subshells
5285 * of the form ( list ), but with any forked children shells.
5286 * I set trap "echo W" WINCH; and then tried:
5287 *
5288 * { echo 1; sleep 20; echo 2; } &
5289 * while true; do echo 1; sleep 20; echo 2; break; done &
5290 * true | { echo 1; sleep 20; echo 2; } | cat
5291 *
5292 * In all these cases sending SIGWINCH to the child shell
5293 * did not run the trap. If I add trap "echo V" WINCH;
5294 * _inside_ group (just before echo 1), it works.
5295 *
5296 * I conclude it means we don't need to pass active traps here.
5297 * Even if we would use signal handlers instead of signal masking
5298 * in order to implement trap handling,
5299 * exec syscall below resets signals to SIG_DFL for us.
5300 */
5301 *pp++ = (char *) "-c";
5302 *pp++ = (char *) s;
5303 if (builtin_argv) {
5304 while (*++builtin_argv)
5305 *pp++ = *builtin_argv;
5306 *pp++ = (char *) "";
5307 }
5308 *pp++ = g_argv0;
5309 while (*g_argv)
5310 *pp++ = *g_argv++;
5311 /* *pp = NULL; - is already there */
5312 pp = environ;
5313
5314 do_exec:
5315 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5316 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5317 execve(bb_busybox_exec_path, argv, pp);
5318 /* Fallback. Useful for init=/bin/hush usage etc */
5319 if (argv[0][0] == '/')
5320 execve(argv[0], argv, pp);
5321 xfunc_error_retval = 127;
5322 bb_error_msg_and_die("can't re-execute the shell");
5323}
5324#endif /* !BB_MMU */
5325
5326
5327static int run_and_free_list(struct pipe *pi);
5328
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005329/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005330 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5331 * end_trigger controls how often we stop parsing
5332 * NUL: parse all, execute, return
5333 * ';': parse till ';' or newline, execute, repeat till EOF
5334 */
5335static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005336{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005337 /* Why we need empty flag?
5338 * An obscure corner case "false; ``; echo $?":
5339 * empty command in `` should still set $? to 0.
5340 * But we can't just set $? to 0 at the start,
5341 * this breaks "false; echo `echo $?`" case.
5342 */
5343 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005344 while (1) {
5345 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005346
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005347 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005348 if (!pipe_list) { /* EOF */
5349 if (empty)
5350 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005351 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005352 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005353 debug_print_tree(pipe_list, 0);
5354 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5355 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005356 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005357 }
Eric Andersen25f27032001-04-26 23:22:31 +00005358}
5359
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005360static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005361{
5362 struct in_str input;
5363 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005364 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005365}
5366
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005367static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005368{
Eric Andersen25f27032001-04-26 23:22:31 +00005369 struct in_str input;
5370 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005371 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005372}
5373
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005374#if ENABLE_HUSH_TICK
5375static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5376{
5377 pid_t pid;
5378 int channel[2];
5379# if !BB_MMU
5380 char **to_free = NULL;
5381# endif
5382
5383 xpipe(channel);
5384 pid = BB_MMU ? xfork() : xvfork();
5385 if (pid == 0) { /* child */
5386 disable_restore_tty_pgrp_on_exit();
5387 /* Process substitution is not considered to be usual
5388 * 'command execution'.
5389 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5390 */
5391 bb_signals(0
5392 + (1 << SIGTSTP)
5393 + (1 << SIGTTIN)
5394 + (1 << SIGTTOU)
5395 , SIG_IGN);
5396 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5397 close(channel[0]); /* NB: close _first_, then move fd! */
5398 xmove_fd(channel[1], 1);
5399 /* Prevent it from trying to handle ctrl-z etc */
5400 IF_HUSH_JOB(G.run_list_level = 1;)
5401 /* Awful hack for `trap` or $(trap).
5402 *
5403 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5404 * contains an example where "trap" is executed in a subshell:
5405 *
5406 * save_traps=$(trap)
5407 * ...
5408 * eval "$save_traps"
5409 *
5410 * Standard does not say that "trap" in subshell shall print
5411 * parent shell's traps. It only says that its output
5412 * must have suitable form, but then, in the above example
5413 * (which is not supposed to be normative), it implies that.
5414 *
5415 * bash (and probably other shell) does implement it
5416 * (traps are reset to defaults, but "trap" still shows them),
5417 * but as a result, "trap" logic is hopelessly messed up:
5418 *
5419 * # trap
5420 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5421 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5422 * # true | trap <--- trap is in subshell - no output (ditto)
5423 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5424 * trap -- 'echo Ho' SIGWINCH
5425 * # echo `(trap)` <--- in subshell in subshell - output
5426 * trap -- 'echo Ho' SIGWINCH
5427 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5428 * trap -- 'echo Ho' SIGWINCH
5429 *
5430 * The rules when to forget and when to not forget traps
5431 * get really complex and nonsensical.
5432 *
5433 * Our solution: ONLY bare $(trap) or `trap` is special.
5434 */
5435 s = skip_whitespace(s);
5436 if (strncmp(s, "trap", 4) == 0
5437 && skip_whitespace(s + 4)[0] == '\0'
5438 ) {
5439 static const char *const argv[] = { NULL, NULL };
5440 builtin_trap((char**)argv);
5441 exit(0); /* not _exit() - we need to fflush */
5442 }
5443# if BB_MMU
5444 reset_traps_to_defaults();
5445 parse_and_run_string(s);
5446 _exit(G.last_exitcode);
5447# else
5448 /* We re-execute after vfork on NOMMU. This makes this script safe:
5449 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5450 * huge=`cat BIG` # was blocking here forever
5451 * echo OK
5452 */
5453 re_execute_shell(&to_free,
5454 s,
5455 G.global_argv[0],
5456 G.global_argv + 1,
5457 NULL);
5458# endif
5459 }
5460
5461 /* parent */
5462 *pid_p = pid;
5463# if ENABLE_HUSH_FAST
5464 G.count_SIGCHLD++;
5465//bb_error_msg("[%d] fork in generate_stream_from_string:"
5466// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5467// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5468# endif
5469 enable_restore_tty_pgrp_on_exit();
5470# if !BB_MMU
5471 free(to_free);
5472# endif
5473 close(channel[1]);
5474 close_on_exec_on(channel[0]);
5475 return xfdopen_for_read(channel[0]);
5476}
5477
5478/* Return code is exit status of the process that is run. */
5479static int process_command_subs(o_string *dest, const char *s)
5480{
5481 FILE *fp;
5482 struct in_str pipe_str;
5483 pid_t pid;
5484 int status, ch, eol_cnt;
5485
5486 fp = generate_stream_from_string(s, &pid);
5487
5488 /* Now send results of command back into original context */
5489 setup_file_in_str(&pipe_str, fp);
5490 eol_cnt = 0;
5491 while ((ch = i_getch(&pipe_str)) != EOF) {
5492 if (ch == '\n') {
5493 eol_cnt++;
5494 continue;
5495 }
5496 while (eol_cnt) {
5497 o_addchr(dest, '\n');
5498 eol_cnt--;
5499 }
5500 o_addQchr(dest, ch);
5501 }
5502
5503 debug_printf("done reading from `cmd` pipe, closing it\n");
5504 fclose(fp);
5505 /* We need to extract exitcode. Test case
5506 * "true; echo `sleep 1; false` $?"
5507 * should print 1 */
5508 safe_waitpid(pid, &status, 0);
5509 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5510 return WEXITSTATUS(status);
5511}
5512#endif /* ENABLE_HUSH_TICK */
5513
5514
5515static void setup_heredoc(struct redir_struct *redir)
5516{
5517 struct fd_pair pair;
5518 pid_t pid;
5519 int len, written;
5520 /* the _body_ of heredoc (misleading field name) */
5521 const char *heredoc = redir->rd_filename;
5522 char *expanded;
5523#if !BB_MMU
5524 char **to_free;
5525#endif
5526
5527 expanded = NULL;
5528 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005529 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005530 if (expanded)
5531 heredoc = expanded;
5532 }
5533 len = strlen(heredoc);
5534
5535 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5536 xpiped_pair(pair);
5537 xmove_fd(pair.rd, redir->rd_fd);
5538
5539 /* Try writing without forking. Newer kernels have
5540 * dynamically growing pipes. Must use non-blocking write! */
5541 ndelay_on(pair.wr);
5542 while (1) {
5543 written = write(pair.wr, heredoc, len);
5544 if (written <= 0)
5545 break;
5546 len -= written;
5547 if (len == 0) {
5548 close(pair.wr);
5549 free(expanded);
5550 return;
5551 }
5552 heredoc += written;
5553 }
5554 ndelay_off(pair.wr);
5555
5556 /* Okay, pipe buffer was not big enough */
5557 /* Note: we must not create a stray child (bastard? :)
5558 * for the unsuspecting parent process. Child creates a grandchild
5559 * and exits before parent execs the process which consumes heredoc
5560 * (that exec happens after we return from this function) */
5561#if !BB_MMU
5562 to_free = NULL;
5563#endif
5564 pid = xvfork();
5565 if (pid == 0) {
5566 /* child */
5567 disable_restore_tty_pgrp_on_exit();
5568 pid = BB_MMU ? xfork() : xvfork();
5569 if (pid != 0)
5570 _exit(0);
5571 /* grandchild */
5572 close(redir->rd_fd); /* read side of the pipe */
5573#if BB_MMU
5574 full_write(pair.wr, heredoc, len); /* may loop or block */
5575 _exit(0);
5576#else
5577 /* Delegate blocking writes to another process */
5578 xmove_fd(pair.wr, STDOUT_FILENO);
5579 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5580#endif
5581 }
5582 /* parent */
5583#if ENABLE_HUSH_FAST
5584 G.count_SIGCHLD++;
5585//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5586#endif
5587 enable_restore_tty_pgrp_on_exit();
5588#if !BB_MMU
5589 free(to_free);
5590#endif
5591 close(pair.wr);
5592 free(expanded);
5593 wait(NULL); /* wait till child has died */
5594}
5595
5596/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5597 * and stderr if they are redirected. */
5598static int setup_redirects(struct command *prog, int squirrel[])
5599{
5600 int openfd, mode;
5601 struct redir_struct *redir;
5602
5603 for (redir = prog->redirects; redir; redir = redir->next) {
5604 if (redir->rd_type == REDIRECT_HEREDOC2) {
5605 /* rd_fd<<HERE case */
5606 if (squirrel && redir->rd_fd < 3
5607 && squirrel[redir->rd_fd] < 0
5608 ) {
5609 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5610 }
5611 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5612 * of the heredoc */
5613 debug_printf_parse("set heredoc '%s'\n",
5614 redir->rd_filename);
5615 setup_heredoc(redir);
5616 continue;
5617 }
5618
5619 if (redir->rd_dup == REDIRFD_TO_FILE) {
5620 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5621 char *p;
5622 if (redir->rd_filename == NULL) {
5623 /* Something went wrong in the parse.
5624 * Pretend it didn't happen */
5625 bb_error_msg("bug in redirect parse");
5626 continue;
5627 }
5628 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005629 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005630 openfd = open_or_warn(p, mode);
5631 free(p);
5632 if (openfd < 0) {
5633 /* this could get lost if stderr has been redirected, but
5634 * bash and ash both lose it as well (though zsh doesn't!) */
5635//what the above comment tries to say?
5636 return 1;
5637 }
5638 } else {
5639 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5640 openfd = redir->rd_dup;
5641 }
5642
5643 if (openfd != redir->rd_fd) {
5644 if (squirrel && redir->rd_fd < 3
5645 && squirrel[redir->rd_fd] < 0
5646 ) {
5647 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5648 }
5649 if (openfd == REDIRFD_CLOSE) {
5650 /* "n>-" means "close me" */
5651 close(redir->rd_fd);
5652 } else {
5653 xdup2(openfd, redir->rd_fd);
5654 if (redir->rd_dup == REDIRFD_TO_FILE)
5655 close(openfd);
5656 }
5657 }
5658 }
5659 return 0;
5660}
5661
5662static void restore_redirects(int squirrel[])
5663{
5664 int i, fd;
5665 for (i = 0; i < 3; i++) {
5666 fd = squirrel[i];
5667 if (fd != -1) {
5668 /* We simply die on error */
5669 xmove_fd(fd, i);
5670 }
5671 }
5672}
5673
5674static char *find_in_path(const char *arg)
5675{
5676 char *ret = NULL;
5677 const char *PATH = get_local_var_value("PATH");
5678
5679 if (!PATH)
5680 return NULL;
5681
5682 while (1) {
5683 const char *end = strchrnul(PATH, ':');
5684 int sz = end - PATH; /* must be int! */
5685
5686 free(ret);
5687 if (sz != 0) {
5688 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5689 } else {
5690 /* We have xxx::yyyy in $PATH,
5691 * it means "use current dir" */
5692 ret = xstrdup(arg);
5693 }
5694 if (access(ret, F_OK) == 0)
5695 break;
5696
5697 if (*end == '\0') {
5698 free(ret);
5699 return NULL;
5700 }
5701 PATH = end + 1;
5702 }
5703
5704 return ret;
5705}
5706
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005707static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005708 const struct built_in_command *x,
5709 const struct built_in_command *end)
5710{
5711 while (x != end) {
5712 if (strcmp(name, x->b_cmd) != 0) {
5713 x++;
5714 continue;
5715 }
5716 debug_printf_exec("found builtin '%s'\n", name);
5717 return x;
5718 }
5719 return NULL;
5720}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005721static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005722{
5723 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5724}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005725static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005726{
5727 const struct built_in_command *x = find_builtin1(name);
5728 if (x)
5729 return x;
5730 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5731}
5732
5733#if ENABLE_HUSH_FUNCTIONS
5734static struct function **find_function_slot(const char *name)
5735{
5736 struct function **funcpp = &G.top_func;
5737 while (*funcpp) {
5738 if (strcmp(name, (*funcpp)->name) == 0) {
5739 break;
5740 }
5741 funcpp = &(*funcpp)->next;
5742 }
5743 return funcpp;
5744}
5745
5746static const struct function *find_function(const char *name)
5747{
5748 const struct function *funcp = *find_function_slot(name);
5749 if (funcp)
5750 debug_printf_exec("found function '%s'\n", name);
5751 return funcp;
5752}
5753
5754/* Note: takes ownership on name ptr */
5755static struct function *new_function(char *name)
5756{
5757 struct function **funcpp = find_function_slot(name);
5758 struct function *funcp = *funcpp;
5759
5760 if (funcp != NULL) {
5761 struct command *cmd = funcp->parent_cmd;
5762 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5763 if (!cmd) {
5764 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5765 free(funcp->name);
5766 /* Note: if !funcp->body, do not free body_as_string!
5767 * This is a special case of "-F name body" function:
5768 * body_as_string was not malloced! */
5769 if (funcp->body) {
5770 free_pipe_list(funcp->body);
5771# if !BB_MMU
5772 free(funcp->body_as_string);
5773# endif
5774 }
5775 } else {
5776 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5777 cmd->argv[0] = funcp->name;
5778 cmd->group = funcp->body;
5779# if !BB_MMU
5780 cmd->group_as_string = funcp->body_as_string;
5781# endif
5782 }
5783 } else {
5784 debug_printf_exec("remembering new function '%s'\n", name);
5785 funcp = *funcpp = xzalloc(sizeof(*funcp));
5786 /*funcp->next = NULL;*/
5787 }
5788
5789 funcp->name = name;
5790 return funcp;
5791}
5792
5793static void unset_func(const char *name)
5794{
5795 struct function **funcpp = find_function_slot(name);
5796 struct function *funcp = *funcpp;
5797
5798 if (funcp != NULL) {
5799 debug_printf_exec("freeing function '%s'\n", funcp->name);
5800 *funcpp = funcp->next;
5801 /* funcp is unlinked now, deleting it.
5802 * Note: if !funcp->body, the function was created by
5803 * "-F name body", do not free ->body_as_string
5804 * and ->name as they were not malloced. */
5805 if (funcp->body) {
5806 free_pipe_list(funcp->body);
5807 free(funcp->name);
5808# if !BB_MMU
5809 free(funcp->body_as_string);
5810# endif
5811 }
5812 free(funcp);
5813 }
5814}
5815
5816# if BB_MMU
5817#define exec_function(to_free, funcp, argv) \
5818 exec_function(funcp, argv)
5819# endif
5820static void exec_function(char ***to_free,
5821 const struct function *funcp,
5822 char **argv) NORETURN;
5823static void exec_function(char ***to_free,
5824 const struct function *funcp,
5825 char **argv)
5826{
5827# if BB_MMU
5828 int n = 1;
5829
5830 argv[0] = G.global_argv[0];
5831 G.global_argv = argv;
5832 while (*++argv)
5833 n++;
5834 G.global_argc = n;
5835 /* On MMU, funcp->body is always non-NULL */
5836 n = run_list(funcp->body);
5837 fflush_all();
5838 _exit(n);
5839# else
5840 re_execute_shell(to_free,
5841 funcp->body_as_string,
5842 G.global_argv[0],
5843 argv + 1,
5844 NULL);
5845# endif
5846}
5847
5848static int run_function(const struct function *funcp, char **argv)
5849{
5850 int rc;
5851 save_arg_t sv;
5852 smallint sv_flg;
5853
5854 save_and_replace_G_args(&sv, argv);
5855
5856 /* "we are in function, ok to use return" */
5857 sv_flg = G.flag_return_in_progress;
5858 G.flag_return_in_progress = -1;
5859# if ENABLE_HUSH_LOCAL
5860 G.func_nest_level++;
5861# endif
5862
5863 /* On MMU, funcp->body is always non-NULL */
5864# if !BB_MMU
5865 if (!funcp->body) {
5866 /* Function defined by -F */
5867 parse_and_run_string(funcp->body_as_string);
5868 rc = G.last_exitcode;
5869 } else
5870# endif
5871 {
5872 rc = run_list(funcp->body);
5873 }
5874
5875# if ENABLE_HUSH_LOCAL
5876 {
5877 struct variable *var;
5878 struct variable **var_pp;
5879
5880 var_pp = &G.top_var;
5881 while ((var = *var_pp) != NULL) {
5882 if (var->func_nest_level < G.func_nest_level) {
5883 var_pp = &var->next;
5884 continue;
5885 }
5886 /* Unexport */
5887 if (var->flg_export)
5888 bb_unsetenv(var->varstr);
5889 /* Remove from global list */
5890 *var_pp = var->next;
5891 /* Free */
5892 if (!var->max_len)
5893 free(var->varstr);
5894 free(var);
5895 }
5896 G.func_nest_level--;
5897 }
5898# endif
5899 G.flag_return_in_progress = sv_flg;
5900
5901 restore_G_args(&sv, argv);
5902
5903 return rc;
5904}
5905#endif /* ENABLE_HUSH_FUNCTIONS */
5906
5907
5908#if BB_MMU
5909#define exec_builtin(to_free, x, argv) \
5910 exec_builtin(x, argv)
5911#else
5912#define exec_builtin(to_free, x, argv) \
5913 exec_builtin(to_free, argv)
5914#endif
5915static void exec_builtin(char ***to_free,
5916 const struct built_in_command *x,
5917 char **argv) NORETURN;
5918static void exec_builtin(char ***to_free,
5919 const struct built_in_command *x,
5920 char **argv)
5921{
5922#if BB_MMU
5923 int rcode = x->b_function(argv);
5924 fflush_all();
5925 _exit(rcode);
5926#else
5927 /* On NOMMU, we must never block!
5928 * Example: { sleep 99 | read line; } & echo Ok
5929 */
5930 re_execute_shell(to_free,
5931 argv[0],
5932 G.global_argv[0],
5933 G.global_argv + 1,
5934 argv);
5935#endif
5936}
5937
5938
5939static void execvp_or_die(char **argv) NORETURN;
5940static void execvp_or_die(char **argv)
5941{
5942 debug_printf_exec("execing '%s'\n", argv[0]);
5943 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5944 execvp(argv[0], argv);
5945 bb_perror_msg("can't execute '%s'", argv[0]);
5946 _exit(127); /* bash compat */
5947}
5948
5949#if ENABLE_HUSH_MODE_X
5950static void dump_cmd_in_x_mode(char **argv)
5951{
5952 if (G_x_mode && argv) {
5953 /* We want to output the line in one write op */
5954 char *buf, *p;
5955 int len;
5956 int n;
5957
5958 len = 3;
5959 n = 0;
5960 while (argv[n])
5961 len += strlen(argv[n++]) + 1;
5962 buf = xmalloc(len);
5963 buf[0] = '+';
5964 p = buf + 1;
5965 n = 0;
5966 while (argv[n])
5967 p += sprintf(p, " %s", argv[n++]);
5968 *p++ = '\n';
5969 *p = '\0';
5970 fputs(buf, stderr);
5971 free(buf);
5972 }
5973}
5974#else
5975# define dump_cmd_in_x_mode(argv) ((void)0)
5976#endif
5977
5978#if BB_MMU
5979#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5980 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5981#define pseudo_exec(nommu_save, command, argv_expanded) \
5982 pseudo_exec(command, argv_expanded)
5983#endif
5984
5985/* Called after [v]fork() in run_pipe, or from builtin_exec.
5986 * Never returns.
5987 * Don't exit() here. If you don't exec, use _exit instead.
5988 * The at_exit handlers apparently confuse the calling process,
5989 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5990static void pseudo_exec_argv(nommu_save_t *nommu_save,
5991 char **argv, int assignment_cnt,
5992 char **argv_expanded) NORETURN;
5993static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5994 char **argv, int assignment_cnt,
5995 char **argv_expanded)
5996{
5997 char **new_env;
5998
5999 new_env = expand_assignments(argv, assignment_cnt);
6000 dump_cmd_in_x_mode(new_env);
6001
6002 if (!argv[assignment_cnt]) {
6003 /* Case when we are here: ... | var=val | ...
6004 * (note that we do not exit early, i.e., do not optimize out
6005 * expand_assignments(): think about ... | var=`sleep 1` | ...
6006 */
6007 free_strings(new_env);
6008 _exit(EXIT_SUCCESS);
6009 }
6010
6011#if BB_MMU
6012 set_vars_and_save_old(new_env);
6013 free(new_env); /* optional */
6014 /* we can also destroy set_vars_and_save_old's return value,
6015 * to save memory */
6016#else
6017 nommu_save->new_env = new_env;
6018 nommu_save->old_vars = set_vars_and_save_old(new_env);
6019#endif
6020
6021 if (argv_expanded) {
6022 argv = argv_expanded;
6023 } else {
6024 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6025#if !BB_MMU
6026 nommu_save->argv = argv;
6027#endif
6028 }
6029 dump_cmd_in_x_mode(argv);
6030
6031#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6032 if (strchr(argv[0], '/') != NULL)
6033 goto skip;
6034#endif
6035
6036 /* Check if the command matches any of the builtins.
6037 * Depending on context, this might be redundant. But it's
6038 * easier to waste a few CPU cycles than it is to figure out
6039 * if this is one of those cases.
6040 */
6041 {
6042 /* On NOMMU, it is more expensive to re-execute shell
6043 * just in order to run echo or test builtin.
6044 * It's better to skip it here and run corresponding
6045 * non-builtin later. */
6046 const struct built_in_command *x;
6047 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6048 if (x) {
6049 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6050 }
6051 }
6052#if ENABLE_HUSH_FUNCTIONS
6053 /* Check if the command matches any functions */
6054 {
6055 const struct function *funcp = find_function(argv[0]);
6056 if (funcp) {
6057 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6058 }
6059 }
6060#endif
6061
6062#if ENABLE_FEATURE_SH_STANDALONE
6063 /* Check if the command matches any busybox applets */
6064 {
6065 int a = find_applet_by_name(argv[0]);
6066 if (a >= 0) {
6067# if BB_MMU /* see above why on NOMMU it is not allowed */
6068 if (APPLET_IS_NOEXEC(a)) {
6069 debug_printf_exec("running applet '%s'\n", argv[0]);
6070 run_applet_no_and_exit(a, argv);
6071 }
6072# endif
6073 /* Re-exec ourselves */
6074 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6075 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6076 execv(bb_busybox_exec_path, argv);
6077 /* If they called chroot or otherwise made the binary no longer
6078 * executable, fall through */
6079 }
6080 }
6081#endif
6082
6083#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6084 skip:
6085#endif
6086 execvp_or_die(argv);
6087}
6088
6089/* Called after [v]fork() in run_pipe
6090 */
6091static void pseudo_exec(nommu_save_t *nommu_save,
6092 struct command *command,
6093 char **argv_expanded) NORETURN;
6094static void pseudo_exec(nommu_save_t *nommu_save,
6095 struct command *command,
6096 char **argv_expanded)
6097{
6098 if (command->argv) {
6099 pseudo_exec_argv(nommu_save, command->argv,
6100 command->assignment_cnt, argv_expanded);
6101 }
6102
6103 if (command->group) {
6104 /* Cases when we are here:
6105 * ( list )
6106 * { list } &
6107 * ... | ( list ) | ...
6108 * ... | { list } | ...
6109 */
6110#if BB_MMU
6111 int rcode;
6112 debug_printf_exec("pseudo_exec: run_list\n");
6113 reset_traps_to_defaults();
6114 rcode = run_list(command->group);
6115 /* OK to leak memory by not calling free_pipe_list,
6116 * since this process is about to exit */
6117 _exit(rcode);
6118#else
6119 re_execute_shell(&nommu_save->argv_from_re_execing,
6120 command->group_as_string,
6121 G.global_argv[0],
6122 G.global_argv + 1,
6123 NULL);
6124#endif
6125 }
6126
6127 /* Case when we are here: ... | >file */
6128 debug_printf_exec("pseudo_exec'ed null command\n");
6129 _exit(EXIT_SUCCESS);
6130}
6131
6132#if ENABLE_HUSH_JOB
6133static const char *get_cmdtext(struct pipe *pi)
6134{
6135 char **argv;
6136 char *p;
6137 int len;
6138
6139 /* This is subtle. ->cmdtext is created only on first backgrounding.
6140 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6141 * On subsequent bg argv is trashed, but we won't use it */
6142 if (pi->cmdtext)
6143 return pi->cmdtext;
6144 argv = pi->cmds[0].argv;
6145 if (!argv || !argv[0]) {
6146 pi->cmdtext = xzalloc(1);
6147 return pi->cmdtext;
6148 }
6149
6150 len = 0;
6151 do {
6152 len += strlen(*argv) + 1;
6153 } while (*++argv);
6154 p = xmalloc(len);
6155 pi->cmdtext = p;
6156 argv = pi->cmds[0].argv;
6157 do {
6158 len = strlen(*argv);
6159 memcpy(p, *argv, len);
6160 p += len;
6161 *p++ = ' ';
6162 } while (*++argv);
6163 p[-1] = '\0';
6164 return pi->cmdtext;
6165}
6166
6167static void insert_bg_job(struct pipe *pi)
6168{
6169 struct pipe *job, **jobp;
6170 int i;
6171
6172 /* Linear search for the ID of the job to use */
6173 pi->jobid = 1;
6174 for (job = G.job_list; job; job = job->next)
6175 if (job->jobid >= pi->jobid)
6176 pi->jobid = job->jobid + 1;
6177
6178 /* Add job to the list of running jobs */
6179 jobp = &G.job_list;
6180 while ((job = *jobp) != NULL)
6181 jobp = &job->next;
6182 job = *jobp = xmalloc(sizeof(*job));
6183
6184 *job = *pi; /* physical copy */
6185 job->next = NULL;
6186 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6187 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6188 for (i = 0; i < pi->num_cmds; i++) {
6189 job->cmds[i].pid = pi->cmds[i].pid;
6190 /* all other fields are not used and stay zero */
6191 }
6192 job->cmdtext = xstrdup(get_cmdtext(pi));
6193
6194 if (G_interactive_fd)
6195 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6196 G.last_jobid = job->jobid;
6197}
6198
6199static void remove_bg_job(struct pipe *pi)
6200{
6201 struct pipe *prev_pipe;
6202
6203 if (pi == G.job_list) {
6204 G.job_list = pi->next;
6205 } else {
6206 prev_pipe = G.job_list;
6207 while (prev_pipe->next != pi)
6208 prev_pipe = prev_pipe->next;
6209 prev_pipe->next = pi->next;
6210 }
6211 if (G.job_list)
6212 G.last_jobid = G.job_list->jobid;
6213 else
6214 G.last_jobid = 0;
6215}
6216
6217/* Remove a backgrounded job */
6218static void delete_finished_bg_job(struct pipe *pi)
6219{
6220 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006221 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006222}
6223#endif /* JOB */
6224
6225/* Check to see if any processes have exited -- if they
6226 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006227static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006228{
6229 int attributes;
6230 int status;
6231#if ENABLE_HUSH_JOB
6232 struct pipe *pi;
6233#endif
6234 pid_t childpid;
6235 int rcode = 0;
6236
6237 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6238
6239 attributes = WUNTRACED;
6240 if (fg_pipe == NULL)
6241 attributes |= WNOHANG;
6242
6243 errno = 0;
6244#if ENABLE_HUSH_FAST
6245 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6246//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6247//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6248 /* There was neither fork nor SIGCHLD since last waitpid */
6249 /* Avoid doing waitpid syscall if possible */
6250 if (!G.we_have_children) {
6251 errno = ECHILD;
6252 return -1;
6253 }
6254 if (fg_pipe == NULL) { /* is WNOHANG set? */
6255 /* We have children, but they did not exit
6256 * or stop yet (we saw no SIGCHLD) */
6257 return 0;
6258 }
6259 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6260 }
6261#endif
6262
6263/* Do we do this right?
6264 * bash-3.00# sleep 20 | false
6265 * <ctrl-Z pressed>
6266 * [3]+ Stopped sleep 20 | false
6267 * bash-3.00# echo $?
6268 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6269 * [hush 1.14.0: yes we do it right]
6270 */
6271 wait_more:
6272 while (1) {
6273 int i;
6274 int dead;
6275
6276#if ENABLE_HUSH_FAST
6277 i = G.count_SIGCHLD;
6278#endif
6279 childpid = waitpid(-1, &status, attributes);
6280 if (childpid <= 0) {
6281 if (childpid && errno != ECHILD)
6282 bb_perror_msg("waitpid");
6283#if ENABLE_HUSH_FAST
6284 else { /* Until next SIGCHLD, waitpid's are useless */
6285 G.we_have_children = (childpid == 0);
6286 G.handled_SIGCHLD = i;
6287//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6288 }
6289#endif
6290 break;
6291 }
6292 dead = WIFEXITED(status) || WIFSIGNALED(status);
6293
6294#if DEBUG_JOBS
6295 if (WIFSTOPPED(status))
6296 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6297 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6298 if (WIFSIGNALED(status))
6299 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6300 childpid, WTERMSIG(status), WEXITSTATUS(status));
6301 if (WIFEXITED(status))
6302 debug_printf_jobs("pid %d exited, exitcode %d\n",
6303 childpid, WEXITSTATUS(status));
6304#endif
6305 /* Were we asked to wait for fg pipe? */
6306 if (fg_pipe) {
6307 for (i = 0; i < fg_pipe->num_cmds; i++) {
6308 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6309 if (fg_pipe->cmds[i].pid != childpid)
6310 continue;
6311 if (dead) {
6312 fg_pipe->cmds[i].pid = 0;
6313 fg_pipe->alive_cmds--;
6314 if (i == fg_pipe->num_cmds - 1) {
6315 /* last process gives overall exitstatus */
6316 rcode = WEXITSTATUS(status);
6317 /* bash prints killer signal's name for *last*
6318 * process in pipe (prints just newline for SIGINT).
6319 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6320 */
6321 if (WIFSIGNALED(status)) {
6322 int sig = WTERMSIG(status);
6323 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6324 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6325 * Maybe we need to use sig | 128? */
6326 rcode = sig + 128;
6327 }
6328 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6329 }
6330 } else {
6331 fg_pipe->cmds[i].is_stopped = 1;
6332 fg_pipe->stopped_cmds++;
6333 }
6334 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6335 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6336 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6337 /* All processes in fg pipe have exited or stopped */
6338/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6339 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6340 * and "killall -STOP cat" */
6341 if (G_interactive_fd) {
6342#if ENABLE_HUSH_JOB
6343 if (fg_pipe->alive_cmds)
6344 insert_bg_job(fg_pipe);
6345#endif
6346 return rcode;
6347 }
6348 if (!fg_pipe->alive_cmds)
6349 return rcode;
6350 }
6351 /* There are still running processes in the fg pipe */
6352 goto wait_more; /* do waitpid again */
6353 }
6354 /* it wasnt fg_pipe, look for process in bg pipes */
6355 }
6356
6357#if ENABLE_HUSH_JOB
6358 /* We asked to wait for bg or orphaned children */
6359 /* No need to remember exitcode in this case */
6360 for (pi = G.job_list; pi; pi = pi->next) {
6361 for (i = 0; i < pi->num_cmds; i++) {
6362 if (pi->cmds[i].pid == childpid)
6363 goto found_pi_and_prognum;
6364 }
6365 }
6366 /* Happens when shell is used as init process (init=/bin/sh) */
6367 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6368 continue; /* do waitpid again */
6369
6370 found_pi_and_prognum:
6371 if (dead) {
6372 /* child exited */
6373 pi->cmds[i].pid = 0;
6374 pi->alive_cmds--;
6375 if (!pi->alive_cmds) {
6376 if (G_interactive_fd)
6377 printf(JOB_STATUS_FORMAT, pi->jobid,
6378 "Done", pi->cmdtext);
6379 delete_finished_bg_job(pi);
6380 }
6381 } else {
6382 /* child stopped */
6383 pi->cmds[i].is_stopped = 1;
6384 pi->stopped_cmds++;
6385 }
6386#endif
6387 } /* while (waitpid succeeds)... */
6388
6389 return rcode;
6390}
6391
6392#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006393static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006394{
6395 pid_t p;
6396 int rcode = checkjobs(fg_pipe);
6397 if (G_saved_tty_pgrp) {
6398 /* Job finished, move the shell to the foreground */
6399 p = getpgrp(); /* our process group id */
6400 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6401 tcsetpgrp(G_interactive_fd, p);
6402 }
6403 return rcode;
6404}
6405#endif
6406
6407/* Start all the jobs, but don't wait for anything to finish.
6408 * See checkjobs().
6409 *
6410 * Return code is normally -1, when the caller has to wait for children
6411 * to finish to determine the exit status of the pipe. If the pipe
6412 * is a simple builtin command, however, the action is done by the
6413 * time run_pipe returns, and the exit code is provided as the
6414 * return value.
6415 *
6416 * Returns -1 only if started some children. IOW: we have to
6417 * mask out retvals of builtins etc with 0xff!
6418 *
6419 * The only case when we do not need to [v]fork is when the pipe
6420 * is single, non-backgrounded, non-subshell command. Examples:
6421 * cmd ; ... { list } ; ...
6422 * cmd && ... { list } && ...
6423 * cmd || ... { list } || ...
6424 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6425 * or (if SH_STANDALONE) an applet, and we can run the { list }
6426 * with run_list. If it isn't one of these, we fork and exec cmd.
6427 *
6428 * Cases when we must fork:
6429 * non-single: cmd | cmd
6430 * backgrounded: cmd & { list } &
6431 * subshell: ( list ) [&]
6432 */
6433#if !ENABLE_HUSH_MODE_X
6434#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6435 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6436#endif
6437static int redirect_and_varexp_helper(char ***new_env_p,
6438 struct variable **old_vars_p,
6439 struct command *command,
6440 int squirrel[3],
6441 char **argv_expanded)
6442{
6443 /* setup_redirects acts on file descriptors, not FILEs.
6444 * This is perfect for work that comes after exec().
6445 * Is it really safe for inline use? Experimentally,
6446 * things seem to work. */
6447 int rcode = setup_redirects(command, squirrel);
6448 if (rcode == 0) {
6449 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6450 *new_env_p = new_env;
6451 dump_cmd_in_x_mode(new_env);
6452 dump_cmd_in_x_mode(argv_expanded);
6453 if (old_vars_p)
6454 *old_vars_p = set_vars_and_save_old(new_env);
6455 }
6456 return rcode;
6457}
6458static NOINLINE int run_pipe(struct pipe *pi)
6459{
6460 static const char *const null_ptr = NULL;
6461
6462 int cmd_no;
6463 int next_infd;
6464 struct command *command;
6465 char **argv_expanded;
6466 char **argv;
6467 /* it is not always needed, but we aim to smaller code */
6468 int squirrel[] = { -1, -1, -1 };
6469 int rcode;
6470
6471 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6472 debug_enter();
6473
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006474 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6475 * Result should be 3 lines: q w e, qwe, q w e
6476 */
6477 G.ifs = get_local_var_value("IFS");
6478 if (!G.ifs)
6479 G.ifs = defifs;
6480
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006481 IF_HUSH_JOB(pi->pgrp = -1;)
6482 pi->stopped_cmds = 0;
6483 command = &pi->cmds[0];
6484 argv_expanded = NULL;
6485
6486 if (pi->num_cmds != 1
6487 || pi->followup == PIPE_BG
6488 || command->cmd_type == CMD_SUBSHELL
6489 ) {
6490 goto must_fork;
6491 }
6492
6493 pi->alive_cmds = 1;
6494
6495 debug_printf_exec(": group:%p argv:'%s'\n",
6496 command->group, command->argv ? command->argv[0] : "NONE");
6497
6498 if (command->group) {
6499#if ENABLE_HUSH_FUNCTIONS
6500 if (command->cmd_type == CMD_FUNCDEF) {
6501 /* "executing" func () { list } */
6502 struct function *funcp;
6503
6504 funcp = new_function(command->argv[0]);
6505 /* funcp->name is already set to argv[0] */
6506 funcp->body = command->group;
6507# if !BB_MMU
6508 funcp->body_as_string = command->group_as_string;
6509 command->group_as_string = NULL;
6510# endif
6511 command->group = NULL;
6512 command->argv[0] = NULL;
6513 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6514 funcp->parent_cmd = command;
6515 command->child_func = funcp;
6516
6517 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6518 debug_leave();
6519 return EXIT_SUCCESS;
6520 }
6521#endif
6522 /* { list } */
6523 debug_printf("non-subshell group\n");
6524 rcode = 1; /* exitcode if redir failed */
6525 if (setup_redirects(command, squirrel) == 0) {
6526 debug_printf_exec(": run_list\n");
6527 rcode = run_list(command->group) & 0xff;
6528 }
6529 restore_redirects(squirrel);
6530 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6531 debug_leave();
6532 debug_printf_exec("run_pipe: return %d\n", rcode);
6533 return rcode;
6534 }
6535
6536 argv = command->argv ? command->argv : (char **) &null_ptr;
6537 {
6538 const struct built_in_command *x;
6539#if ENABLE_HUSH_FUNCTIONS
6540 const struct function *funcp;
6541#else
6542 enum { funcp = 0 };
6543#endif
6544 char **new_env = NULL;
6545 struct variable *old_vars = NULL;
6546
6547 if (argv[command->assignment_cnt] == NULL) {
6548 /* Assignments, but no command */
6549 /* Ensure redirects take effect (that is, create files).
6550 * Try "a=t >file" */
6551#if 0 /* A few cases in testsuite fail with this code. FIXME */
6552 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6553 /* Set shell variables */
6554 if (new_env) {
6555 argv = new_env;
6556 while (*argv) {
6557 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6558 /* Do we need to flag set_local_var() errors?
6559 * "assignment to readonly var" and "putenv error"
6560 */
6561 argv++;
6562 }
6563 }
6564 /* Redirect error sets $? to 1. Otherwise,
6565 * if evaluating assignment value set $?, retain it.
6566 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6567 if (rcode == 0)
6568 rcode = G.last_exitcode;
6569 /* Exit, _skipping_ variable restoring code: */
6570 goto clean_up_and_ret0;
6571
6572#else /* Older, bigger, but more correct code */
6573
6574 rcode = setup_redirects(command, squirrel);
6575 restore_redirects(squirrel);
6576 /* Set shell variables */
6577 if (G_x_mode)
6578 bb_putchar_stderr('+');
6579 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006580 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006581 if (G_x_mode)
6582 fprintf(stderr, " %s", p);
6583 debug_printf_exec("set shell var:'%s'->'%s'\n",
6584 *argv, p);
6585 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6586 /* Do we need to flag set_local_var() errors?
6587 * "assignment to readonly var" and "putenv error"
6588 */
6589 argv++;
6590 }
6591 if (G_x_mode)
6592 bb_putchar_stderr('\n');
6593 /* Redirect error sets $? to 1. Otherwise,
6594 * if evaluating assignment value set $?, retain it.
6595 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6596 if (rcode == 0)
6597 rcode = G.last_exitcode;
6598 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6599 debug_leave();
6600 debug_printf_exec("run_pipe: return %d\n", rcode);
6601 return rcode;
6602#endif
6603 }
6604
6605 /* Expand the rest into (possibly) many strings each */
6606 if (0) {}
6607#if ENABLE_HUSH_BASH_COMPAT
6608 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6609 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6610 }
6611#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006612 else {
6613 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6614 }
6615
6616 /* if someone gives us an empty string: `cmd with empty output` */
6617 if (!argv_expanded[0]) {
6618 free(argv_expanded);
6619 debug_leave();
6620 return G.last_exitcode;
6621 }
6622
6623 x = find_builtin(argv_expanded[0]);
6624#if ENABLE_HUSH_FUNCTIONS
6625 funcp = NULL;
6626 if (!x)
6627 funcp = find_function(argv_expanded[0]);
6628#endif
6629 if (x || funcp) {
6630 if (!funcp) {
6631 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6632 debug_printf("exec with redirects only\n");
6633 rcode = setup_redirects(command, NULL);
6634 goto clean_up_and_ret1;
6635 }
6636 }
6637 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6638 if (rcode == 0) {
6639 if (!funcp) {
6640 debug_printf_exec(": builtin '%s' '%s'...\n",
6641 x->b_cmd, argv_expanded[1]);
6642 rcode = x->b_function(argv_expanded) & 0xff;
6643 fflush_all();
6644 }
6645#if ENABLE_HUSH_FUNCTIONS
6646 else {
6647# if ENABLE_HUSH_LOCAL
6648 struct variable **sv;
6649 sv = G.shadowed_vars_pp;
6650 G.shadowed_vars_pp = &old_vars;
6651# endif
6652 debug_printf_exec(": function '%s' '%s'...\n",
6653 funcp->name, argv_expanded[1]);
6654 rcode = run_function(funcp, argv_expanded) & 0xff;
6655# if ENABLE_HUSH_LOCAL
6656 G.shadowed_vars_pp = sv;
6657# endif
6658 }
6659#endif
6660 }
6661 clean_up_and_ret:
6662 unset_vars(new_env);
6663 add_vars(old_vars);
6664/* clean_up_and_ret0: */
6665 restore_redirects(squirrel);
6666 clean_up_and_ret1:
6667 free(argv_expanded);
6668 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6669 debug_leave();
6670 debug_printf_exec("run_pipe return %d\n", rcode);
6671 return rcode;
6672 }
6673
6674 if (ENABLE_FEATURE_SH_STANDALONE) {
6675 int n = find_applet_by_name(argv_expanded[0]);
6676 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6677 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6678 if (rcode == 0) {
6679 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6680 argv_expanded[0], argv_expanded[1]);
6681 rcode = run_nofork_applet(n, argv_expanded);
6682 }
6683 goto clean_up_and_ret;
6684 }
6685 }
6686 /* It is neither builtin nor applet. We must fork. */
6687 }
6688
6689 must_fork:
6690 /* NB: argv_expanded may already be created, and that
6691 * might include `cmd` runs! Do not rerun it! We *must*
6692 * use argv_expanded if it's non-NULL */
6693
6694 /* Going to fork a child per each pipe member */
6695 pi->alive_cmds = 0;
6696 next_infd = 0;
6697
6698 cmd_no = 0;
6699 while (cmd_no < pi->num_cmds) {
6700 struct fd_pair pipefds;
6701#if !BB_MMU
6702 volatile nommu_save_t nommu_save;
6703 nommu_save.new_env = NULL;
6704 nommu_save.old_vars = NULL;
6705 nommu_save.argv = NULL;
6706 nommu_save.argv_from_re_execing = NULL;
6707#endif
6708 command = &pi->cmds[cmd_no];
6709 cmd_no++;
6710 if (command->argv) {
6711 debug_printf_exec(": pipe member '%s' '%s'...\n",
6712 command->argv[0], command->argv[1]);
6713 } else {
6714 debug_printf_exec(": pipe member with no argv\n");
6715 }
6716
6717 /* pipes are inserted between pairs of commands */
6718 pipefds.rd = 0;
6719 pipefds.wr = 1;
6720 if (cmd_no < pi->num_cmds)
6721 xpiped_pair(pipefds);
6722
6723 command->pid = BB_MMU ? fork() : vfork();
6724 if (!command->pid) { /* child */
6725#if ENABLE_HUSH_JOB
6726 disable_restore_tty_pgrp_on_exit();
6727 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6728
6729 /* Every child adds itself to new process group
6730 * with pgid == pid_of_first_child_in_pipe */
6731 if (G.run_list_level == 1 && G_interactive_fd) {
6732 pid_t pgrp;
6733 pgrp = pi->pgrp;
6734 if (pgrp < 0) /* true for 1st process only */
6735 pgrp = getpid();
6736 if (setpgid(0, pgrp) == 0
6737 && pi->followup != PIPE_BG
6738 && G_saved_tty_pgrp /* we have ctty */
6739 ) {
6740 /* We do it in *every* child, not just first,
6741 * to avoid races */
6742 tcsetpgrp(G_interactive_fd, pgrp);
6743 }
6744 }
6745#endif
6746 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6747 /* 1st cmd in backgrounded pipe
6748 * should have its stdin /dev/null'ed */
6749 close(0);
6750 if (open(bb_dev_null, O_RDONLY))
6751 xopen("/", O_RDONLY);
6752 } else {
6753 xmove_fd(next_infd, 0);
6754 }
6755 xmove_fd(pipefds.wr, 1);
6756 if (pipefds.rd > 1)
6757 close(pipefds.rd);
6758 /* Like bash, explicit redirects override pipes,
6759 * and the pipe fd is available for dup'ing. */
6760 if (setup_redirects(command, NULL))
6761 _exit(1);
6762
6763 /* Restore default handlers just prior to exec */
6764 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6765
6766 /* Stores to nommu_save list of env vars putenv'ed
6767 * (NOMMU, on MMU we don't need that) */
6768 /* cast away volatility... */
6769 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6770 /* pseudo_exec() does not return */
6771 }
6772
6773 /* parent or error */
6774#if ENABLE_HUSH_FAST
6775 G.count_SIGCHLD++;
6776//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6777#endif
6778 enable_restore_tty_pgrp_on_exit();
6779#if !BB_MMU
6780 /* Clean up after vforked child */
6781 free(nommu_save.argv);
6782 free(nommu_save.argv_from_re_execing);
6783 unset_vars(nommu_save.new_env);
6784 add_vars(nommu_save.old_vars);
6785#endif
6786 free(argv_expanded);
6787 argv_expanded = NULL;
6788 if (command->pid < 0) { /* [v]fork failed */
6789 /* Clearly indicate, was it fork or vfork */
6790 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6791 } else {
6792 pi->alive_cmds++;
6793#if ENABLE_HUSH_JOB
6794 /* Second and next children need to know pid of first one */
6795 if (pi->pgrp < 0)
6796 pi->pgrp = command->pid;
6797#endif
6798 }
6799
6800 if (cmd_no > 1)
6801 close(next_infd);
6802 if (cmd_no < pi->num_cmds)
6803 close(pipefds.wr);
6804 /* Pass read (output) pipe end to next iteration */
6805 next_infd = pipefds.rd;
6806 }
6807
6808 if (!pi->alive_cmds) {
6809 debug_leave();
6810 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6811 return 1;
6812 }
6813
6814 debug_leave();
6815 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6816 return -1;
6817}
6818
6819#ifndef debug_print_tree
6820static void debug_print_tree(struct pipe *pi, int lvl)
6821{
6822 static const char *const PIPE[] = {
6823 [PIPE_SEQ] = "SEQ",
6824 [PIPE_AND] = "AND",
6825 [PIPE_OR ] = "OR" ,
6826 [PIPE_BG ] = "BG" ,
6827 };
6828 static const char *RES[] = {
6829 [RES_NONE ] = "NONE" ,
6830# if ENABLE_HUSH_IF
6831 [RES_IF ] = "IF" ,
6832 [RES_THEN ] = "THEN" ,
6833 [RES_ELIF ] = "ELIF" ,
6834 [RES_ELSE ] = "ELSE" ,
6835 [RES_FI ] = "FI" ,
6836# endif
6837# if ENABLE_HUSH_LOOPS
6838 [RES_FOR ] = "FOR" ,
6839 [RES_WHILE] = "WHILE",
6840 [RES_UNTIL] = "UNTIL",
6841 [RES_DO ] = "DO" ,
6842 [RES_DONE ] = "DONE" ,
6843# endif
6844# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6845 [RES_IN ] = "IN" ,
6846# endif
6847# if ENABLE_HUSH_CASE
6848 [RES_CASE ] = "CASE" ,
6849 [RES_CASE_IN ] = "CASE_IN" ,
6850 [RES_MATCH] = "MATCH",
6851 [RES_CASE_BODY] = "CASE_BODY",
6852 [RES_ESAC ] = "ESAC" ,
6853# endif
6854 [RES_XXXX ] = "XXXX" ,
6855 [RES_SNTX ] = "SNTX" ,
6856 };
6857 static const char *const CMDTYPE[] = {
6858 "{}",
6859 "()",
6860 "[noglob]",
6861# if ENABLE_HUSH_FUNCTIONS
6862 "func()",
6863# endif
6864 };
6865
6866 int pin, prn;
6867
6868 pin = 0;
6869 while (pi) {
6870 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6871 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6872 prn = 0;
6873 while (prn < pi->num_cmds) {
6874 struct command *command = &pi->cmds[prn];
6875 char **argv = command->argv;
6876
6877 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6878 lvl*2, "", prn,
6879 command->assignment_cnt);
6880 if (command->group) {
6881 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6882 CMDTYPE[command->cmd_type],
6883 argv
6884# if !BB_MMU
6885 , " group_as_string:", command->group_as_string
6886# else
6887 , "", ""
6888# endif
6889 );
6890 debug_print_tree(command->group, lvl+1);
6891 prn++;
6892 continue;
6893 }
6894 if (argv) while (*argv) {
6895 fprintf(stderr, " '%s'", *argv);
6896 argv++;
6897 }
6898 fprintf(stderr, "\n");
6899 prn++;
6900 }
6901 pi = pi->next;
6902 pin++;
6903 }
6904}
6905#endif /* debug_print_tree */
6906
6907/* NB: called by pseudo_exec, and therefore must not modify any
6908 * global data until exec/_exit (we can be a child after vfork!) */
6909static int run_list(struct pipe *pi)
6910{
6911#if ENABLE_HUSH_CASE
6912 char *case_word = NULL;
6913#endif
6914#if ENABLE_HUSH_LOOPS
6915 struct pipe *loop_top = NULL;
6916 char **for_lcur = NULL;
6917 char **for_list = NULL;
6918#endif
6919 smallint last_followup;
6920 smalluint rcode;
6921#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6922 smalluint cond_code = 0;
6923#else
6924 enum { cond_code = 0 };
6925#endif
6926#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02006927 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006928 smallint last_rword; /* ditto */
6929#endif
6930
6931 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6932 debug_enter();
6933
6934#if ENABLE_HUSH_LOOPS
6935 /* Check syntax for "for" */
6936 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6937 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6938 continue;
6939 /* current word is FOR or IN (BOLD in comments below) */
6940 if (cpipe->next == NULL) {
6941 syntax_error("malformed for");
6942 debug_leave();
6943 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6944 return 1;
6945 }
6946 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6947 if (cpipe->next->res_word == RES_DO)
6948 continue;
6949 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6950 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6951 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6952 ) {
6953 syntax_error("malformed for");
6954 debug_leave();
6955 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6956 return 1;
6957 }
6958 }
6959#endif
6960
6961 /* Past this point, all code paths should jump to ret: label
6962 * in order to return, no direct "return" statements please.
6963 * This helps to ensure that no memory is leaked. */
6964
6965#if ENABLE_HUSH_JOB
6966 G.run_list_level++;
6967#endif
6968
6969#if HAS_KEYWORDS
6970 rword = RES_NONE;
6971 last_rword = RES_XXXX;
6972#endif
6973 last_followup = PIPE_SEQ;
6974 rcode = G.last_exitcode;
6975
6976 /* Go through list of pipes, (maybe) executing them. */
6977 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6978 if (G.flag_SIGINT)
6979 break;
6980
6981 IF_HAS_KEYWORDS(rword = pi->res_word;)
6982 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6983 rword, cond_code, last_rword);
6984#if ENABLE_HUSH_LOOPS
6985 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6986 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6987 ) {
6988 /* start of a loop: remember where loop starts */
6989 loop_top = pi;
6990 G.depth_of_loop++;
6991 }
6992#endif
6993 /* Still in the same "if...", "then..." or "do..." branch? */
6994 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6995 if ((rcode == 0 && last_followup == PIPE_OR)
6996 || (rcode != 0 && last_followup == PIPE_AND)
6997 ) {
6998 /* It is "<true> || CMD" or "<false> && CMD"
6999 * and we should not execute CMD */
7000 debug_printf_exec("skipped cmd because of || or &&\n");
7001 last_followup = pi->followup;
7002 continue;
7003 }
7004 }
7005 last_followup = pi->followup;
7006 IF_HAS_KEYWORDS(last_rword = rword;)
7007#if ENABLE_HUSH_IF
7008 if (cond_code) {
7009 if (rword == RES_THEN) {
7010 /* if false; then ... fi has exitcode 0! */
7011 G.last_exitcode = rcode = EXIT_SUCCESS;
7012 /* "if <false> THEN cmd": skip cmd */
7013 continue;
7014 }
7015 } else {
7016 if (rword == RES_ELSE || rword == RES_ELIF) {
7017 /* "if <true> then ... ELSE/ELIF cmd":
7018 * skip cmd and all following ones */
7019 break;
7020 }
7021 }
7022#endif
7023#if ENABLE_HUSH_LOOPS
7024 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7025 if (!for_lcur) {
7026 /* first loop through for */
7027
7028 static const char encoded_dollar_at[] ALIGN1 = {
7029 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7030 }; /* encoded representation of "$@" */
7031 static const char *const encoded_dollar_at_argv[] = {
7032 encoded_dollar_at, NULL
7033 }; /* argv list with one element: "$@" */
7034 char **vals;
7035
7036 vals = (char**)encoded_dollar_at_argv;
7037 if (pi->next->res_word == RES_IN) {
7038 /* if no variable values after "in" we skip "for" */
7039 if (!pi->next->cmds[0].argv) {
7040 G.last_exitcode = rcode = EXIT_SUCCESS;
7041 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7042 break;
7043 }
7044 vals = pi->next->cmds[0].argv;
7045 } /* else: "for var; do..." -> assume "$@" list */
7046 /* create list of variable values */
7047 debug_print_strings("for_list made from", vals);
7048 for_list = expand_strvec_to_strvec(vals);
7049 for_lcur = for_list;
7050 debug_print_strings("for_list", for_list);
7051 }
7052 if (!*for_lcur) {
7053 /* "for" loop is over, clean up */
7054 free(for_list);
7055 for_list = NULL;
7056 for_lcur = NULL;
7057 break;
7058 }
7059 /* Insert next value from for_lcur */
7060 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7061 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7062 continue;
7063 }
7064 if (rword == RES_IN) {
7065 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7066 }
7067 if (rword == RES_DONE) {
7068 continue; /* "done" has no cmds too */
7069 }
7070#endif
7071#if ENABLE_HUSH_CASE
7072 if (rword == RES_CASE) {
7073 case_word = expand_strvec_to_string(pi->cmds->argv);
7074 continue;
7075 }
7076 if (rword == RES_MATCH) {
7077 char **argv;
7078
7079 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7080 break;
7081 /* all prev words didn't match, does this one match? */
7082 argv = pi->cmds->argv;
7083 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007084 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007085 /* TODO: which FNM_xxx flags to use? */
7086 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7087 free(pattern);
7088 if (cond_code == 0) { /* match! we will execute this branch */
7089 free(case_word); /* make future "word)" stop */
7090 case_word = NULL;
7091 break;
7092 }
7093 argv++;
7094 }
7095 continue;
7096 }
7097 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7098 if (cond_code != 0)
7099 continue; /* not matched yet, skip this pipe */
7100 }
7101#endif
7102 /* Just pressing <enter> in shell should check for jobs.
7103 * OTOH, in non-interactive shell this is useless
7104 * and only leads to extra job checks */
7105 if (pi->num_cmds == 0) {
7106 if (G_interactive_fd)
7107 goto check_jobs_and_continue;
7108 continue;
7109 }
7110
7111 /* After analyzing all keywords and conditions, we decided
7112 * to execute this pipe. NB: have to do checkjobs(NULL)
7113 * after run_pipe to collect any background children,
7114 * even if list execution is to be stopped. */
7115 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7116 {
7117 int r;
7118#if ENABLE_HUSH_LOOPS
7119 G.flag_break_continue = 0;
7120#endif
7121 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7122 if (r != -1) {
7123 /* We ran a builtin, function, or group.
7124 * rcode is already known
7125 * and we don't need to wait for anything. */
7126 G.last_exitcode = rcode;
7127 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7128 check_and_run_traps(0);
7129#if ENABLE_HUSH_LOOPS
7130 /* Was it "break" or "continue"? */
7131 if (G.flag_break_continue) {
7132 smallint fbc = G.flag_break_continue;
7133 /* We might fall into outer *loop*,
7134 * don't want to break it too */
7135 if (loop_top) {
7136 G.depth_break_continue--;
7137 if (G.depth_break_continue == 0)
7138 G.flag_break_continue = 0;
7139 /* else: e.g. "continue 2" should *break* once, *then* continue */
7140 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7141 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7142 goto check_jobs_and_break;
7143 /* "continue": simulate end of loop */
7144 rword = RES_DONE;
7145 continue;
7146 }
7147#endif
7148#if ENABLE_HUSH_FUNCTIONS
7149 if (G.flag_return_in_progress == 1) {
7150 /* same as "goto check_jobs_and_break" */
7151 checkjobs(NULL);
7152 break;
7153 }
7154#endif
7155 } else if (pi->followup == PIPE_BG) {
7156 /* What does bash do with attempts to background builtins? */
7157 /* even bash 3.2 doesn't do that well with nested bg:
7158 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7159 * I'm NOT treating inner &'s as jobs */
7160 check_and_run_traps(0);
7161#if ENABLE_HUSH_JOB
7162 if (G.run_list_level == 1)
7163 insert_bg_job(pi);
7164#endif
7165 /* Last command's pid goes to $! */
7166 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7167 G.last_exitcode = rcode = EXIT_SUCCESS;
7168 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7169 } else {
7170#if ENABLE_HUSH_JOB
7171 if (G.run_list_level == 1 && G_interactive_fd) {
7172 /* Waits for completion, then fg's main shell */
7173 rcode = checkjobs_and_fg_shell(pi);
7174 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7175 check_and_run_traps(0);
7176 } else
7177#endif
7178 { /* This one just waits for completion */
7179 rcode = checkjobs(pi);
7180 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7181 check_and_run_traps(0);
7182 }
7183 G.last_exitcode = rcode;
7184 }
7185 }
7186
7187 /* Analyze how result affects subsequent commands */
7188#if ENABLE_HUSH_IF
7189 if (rword == RES_IF || rword == RES_ELIF)
7190 cond_code = rcode;
7191#endif
7192#if ENABLE_HUSH_LOOPS
7193 /* Beware of "while false; true; do ..."! */
7194 if (pi->next && pi->next->res_word == RES_DO) {
7195 if (rword == RES_WHILE) {
7196 if (rcode) {
7197 /* "while false; do...done" - exitcode 0 */
7198 G.last_exitcode = rcode = EXIT_SUCCESS;
7199 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7200 goto check_jobs_and_break;
7201 }
7202 }
7203 if (rword == RES_UNTIL) {
7204 if (!rcode) {
7205 debug_printf_exec(": until expr is true: breaking\n");
7206 check_jobs_and_break:
7207 checkjobs(NULL);
7208 break;
7209 }
7210 }
7211 }
7212#endif
7213
7214 check_jobs_and_continue:
7215 checkjobs(NULL);
7216 } /* for (pi) */
7217
7218#if ENABLE_HUSH_JOB
7219 G.run_list_level--;
7220#endif
7221#if ENABLE_HUSH_LOOPS
7222 if (loop_top)
7223 G.depth_of_loop--;
7224 free(for_list);
7225#endif
7226#if ENABLE_HUSH_CASE
7227 free(case_word);
7228#endif
7229 debug_leave();
7230 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7231 return rcode;
7232}
7233
7234/* Select which version we will use */
7235static int run_and_free_list(struct pipe *pi)
7236{
7237 int rcode = 0;
7238 debug_printf_exec("run_and_free_list entered\n");
7239 if (!G.n_mode) {
7240 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7241 rcode = run_list(pi);
7242 }
7243 /* free_pipe_list has the side effect of clearing memory.
7244 * In the long run that function can be merged with run_list,
7245 * but doing that now would hobble the debugging effort. */
7246 free_pipe_list(pi);
7247 debug_printf_exec("run_and_free_list return %d\n", rcode);
7248 return rcode;
7249}
7250
7251
Denis Vlasenkof9375282009-04-05 19:13:39 +00007252/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007253static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007254{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007255 unsigned sig;
7256 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007257 sigset_t old_blocked_set;
7258
7259 if (!G.inherited_set_is_saved) {
7260 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7261 G.inherited_set = G.blocked_set;
7262 }
7263 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007264
Denis Vlasenkof9375282009-04-05 19:13:39 +00007265 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007266 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007267 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007268 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007269 mask |= SPECIAL_JOB_SIGS;
7270 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007271 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007272
Denis Vlasenkof9375282009-04-05 19:13:39 +00007273 sig = 0;
7274 while (mask) {
7275 if (mask & 1)
7276 sigaddset(&G.blocked_set, sig);
7277 mask >>= 1;
7278 sig++;
7279 }
7280 sigdelset(&G.blocked_set, SIGCHLD);
7281
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007282 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7283 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7284
Denis Vlasenkof9375282009-04-05 19:13:39 +00007285 /* POSIX allows shell to re-enable SIGCHLD
7286 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007287#if ENABLE_HUSH_FAST
7288 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007289 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007290 signal(SIGCHLD, SIGCHLD_handler);
7291#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007292 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007293 signal(SIGCHLD, SIG_DFL);
7294#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007295
7296 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007297}
7298
7299#if ENABLE_HUSH_JOB
7300/* helper */
7301static void maybe_set_to_sigexit(int sig)
7302{
7303 void (*handler)(int);
7304 /* non_DFL_mask'ed signals are, well, masked,
7305 * no need to set handler for them.
7306 */
7307 if (!((G.non_DFL_mask >> sig) & 1)) {
7308 handler = signal(sig, sigexit);
7309 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7310 signal(sig, handler);
7311 }
7312}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007313/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007314static void set_fatal_handlers(void)
7315{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007316 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007317 if (HUSH_DEBUG) {
7318 maybe_set_to_sigexit(SIGILL );
7319 maybe_set_to_sigexit(SIGFPE );
7320 maybe_set_to_sigexit(SIGBUS );
7321 maybe_set_to_sigexit(SIGSEGV);
7322 maybe_set_to_sigexit(SIGTRAP);
7323 } /* else: hush is perfect. what SEGV? */
7324 maybe_set_to_sigexit(SIGABRT);
7325 /* bash 3.2 seems to handle these just like 'fatal' ones */
7326 maybe_set_to_sigexit(SIGPIPE);
7327 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007328 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007329 * if we aren't interactive... but in this case
7330 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007331 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007332 /*maybe_set_to_sigexit(SIGTERM);*/
7333 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007334}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007335#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007336
Denis Vlasenkod5762932009-03-31 11:22:57 +00007337static int set_mode(const char cstate, const char mode)
7338{
7339 int state = (cstate == '-' ? 1 : 0);
7340 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007341 case 'n': G.n_mode = state; break;
7342 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007343 default: return EXIT_FAILURE;
7344 }
7345 return EXIT_SUCCESS;
7346}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007347
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007348int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007349int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007350{
7351 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007352 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007353 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007354 struct variable *cur_var;
Denys Vlasenko52e460b2010-09-16 16:12:00 +02007355 struct variable shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007356
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007357 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007358 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007359 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007360#if !BB_MMU
7361 G.argv0_for_re_execing = argv[0];
7362#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007363 /* Deal with HUSH_VERSION */
Denys Vlasenko52e460b2010-09-16 16:12:00 +02007364 memset(&shell_ver, 0, sizeof(shell_ver));
7365 shell_ver.flg_export = 1;
7366 shell_ver.flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007367 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007368 * therefore we xstrdup: */
Denys Vlasenko52e460b2010-09-16 16:12:00 +02007369 shell_ver.varstr = xstrdup(hush_version_str),
7370 G.top_var = &shell_ver;
Denys Vlasenko605067b2010-09-06 12:10:51 +02007371 /* Create shell local variables from the values
7372 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007373 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007374 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007375 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007376 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007377 if (e) while (*e) {
7378 char *value = strchr(*e, '=');
7379 if (value) { /* paranoia */
7380 cur_var->next = xzalloc(sizeof(*cur_var));
7381 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007382 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007383 cur_var->max_len = strlen(*e);
7384 cur_var->flg_export = 1;
7385 }
7386 e++;
7387 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007388 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko52e460b2010-09-16 16:12:00 +02007389 debug_printf_env("putenv '%s'\n", shell_ver.varstr);
7390 putenv(shell_ver.varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007391
7392 /* Export PWD */
7393 set_pwd_var(/*exp:*/ 1);
7394 /* bash also exports SHLVL and _,
7395 * and sets (but doesn't export) the following variables:
7396 * BASH=/bin/bash
7397 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7398 * BASH_VERSION='3.2.0(1)-release'
7399 * HOSTTYPE=i386
7400 * MACHTYPE=i386-pc-linux-gnu
7401 * OSTYPE=linux-gnu
7402 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007403 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007404 * EUID=<NNNNN>
7405 * UID=<NNNNN>
7406 * GROUPS=()
7407 * LINES=<NNN>
7408 * COLUMNS=<NNN>
7409 * BASH_ARGC=()
7410 * BASH_ARGV=()
7411 * BASH_LINENO=()
7412 * BASH_SOURCE=()
7413 * DIRSTACK=()
7414 * PIPESTATUS=([0]="0")
7415 * HISTFILE=/<xxx>/.bash_history
7416 * HISTFILESIZE=500
7417 * HISTSIZE=500
7418 * MAILCHECK=60
7419 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7420 * SHELL=/bin/bash
7421 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7422 * TERM=dumb
7423 * OPTERR=1
7424 * OPTIND=1
7425 * IFS=$' \t\n'
7426 * PS1='\s-\v\$ '
7427 * PS2='> '
7428 * PS4='+ '
7429 */
7430
Denis Vlasenko38f63192007-01-22 09:03:07 +00007431#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007432 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007433# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7434 {
7435 const char *hp = get_local_var_value("HISTFILE");
7436 if (!hp) {
7437 hp = get_local_var_value("HOME");
7438 if (hp) {
7439 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7440 //set_local_var(xasprintf("HISTFILE=%s", ...));
7441 }
7442 }
7443 }
7444# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007445#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007446
Denis Vlasenko87a86552008-07-29 19:43:10 +00007447 G.global_argc = argc;
7448 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007449 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007450 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007451
Denis Vlasenkoed782372009-04-10 00:45:02 +00007452 if (setjmp(die_jmp)) {
7453 /* xfunc has failed! die die die */
7454 /* no EXIT traps, this is an escape hatch! */
7455 G.exiting = 1;
7456 hush_exit(xfunc_error_retval);
7457 }
7458
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007459 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007460 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007461 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007462 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007463 * in order to intercept (more) signals.
7464 */
7465
7466 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007467 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007468 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007469 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007470 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007471#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007472 "<:$:R:V:"
7473# if ENABLE_HUSH_FUNCTIONS
7474 "F:"
7475# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007476#endif
7477 );
7478 if (opt <= 0)
7479 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007480 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007481 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007482 /* Possibilities:
7483 * sh ... -c 'script'
7484 * sh ... -c 'script' ARG0 [ARG1...]
7485 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007486 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007487 * "" needs to be replaced with NULL
7488 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007489 * Note: the form without ARG0 never happens:
7490 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007491 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007492 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007493 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007494 G.root_ppid = getppid();
7495 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007496 G.global_argv = argv + optind;
7497 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007498 if (builtin_argc) {
7499 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7500 const struct built_in_command *x;
7501
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007502 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007503 x = find_builtin(optarg);
7504 if (x) { /* paranoia */
7505 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7506 G.global_argv += builtin_argc;
7507 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007508 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007509 }
7510 goto final_return;
7511 }
7512 if (!G.global_argv[0]) {
7513 /* -c 'script' (no params): prevent empty $0 */
7514 G.global_argv--; /* points to argv[i] of 'script' */
7515 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007516 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007517 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007518 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007519 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007520 goto final_return;
7521 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007522 /* Well, we cannot just declare interactiveness,
7523 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007524 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007525 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007526 case 's':
7527 /* "-s" means "read from stdin", but this is how we always
7528 * operate, so simply do nothing here. */
7529 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007530#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007531 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007532 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007533 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007534 case '$': {
7535 unsigned long long empty_trap_mask;
7536
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007537 G.root_pid = bb_strtou(optarg, &optarg, 16);
7538 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007539 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7540 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007541 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7542 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007543 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007544 optarg++;
7545 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007546 optarg++;
7547 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7548 if (empty_trap_mask != 0) {
7549 int sig;
7550 init_sigmasks();
7551 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7552 for (sig = 1; sig < NSIG; sig++) {
7553 if (empty_trap_mask & (1LL << sig)) {
7554 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7555 sigaddset(&G.blocked_set, sig);
7556 }
7557 }
7558 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7559 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007560# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007561 optarg++;
7562 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007563# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007564 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007565 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007566 case 'R':
7567 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007568 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007569 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007570# if ENABLE_HUSH_FUNCTIONS
7571 case 'F': {
7572 struct function *funcp = new_function(optarg);
7573 /* funcp->name is already set to optarg */
7574 /* funcp->body is set to NULL. It's a special case. */
7575 funcp->body_as_string = argv[optind];
7576 optind++;
7577 break;
7578 }
7579# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007580#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007581 case 'n':
7582 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007583 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007584 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007585 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007586#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007587 fprintf(stderr, "Usage: sh [FILE]...\n"
7588 " or: sh -c command [args]...\n\n");
7589 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007590#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007591 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007592#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007593 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007594 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007595
Denys Vlasenkodea47882009-10-09 15:40:49 +02007596 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007597 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007598 G.root_ppid = getppid();
7599 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007600
7601 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007602 if (argv[0] && argv[0][0] == '-') {
7603 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007604 debug_printf("sourcing /etc/profile\n");
7605 input = fopen_for_read("/etc/profile");
7606 if (input != NULL) {
7607 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007608 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007609 parse_and_run_file(input);
7610 fclose(input);
7611 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007612 /* bash: after sourcing /etc/profile,
7613 * tries to source (in the given order):
7614 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007615 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007616 * bash also sources ~/.bash_logout on exit.
7617 * If called as sh, skips .bash_XXX files.
7618 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007619 }
7620
Denis Vlasenkof9375282009-04-05 19:13:39 +00007621 if (argv[optind]) {
7622 FILE *input;
7623 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007624 * "bash <script>" (which is never interactive (unless -i?))
7625 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007626 * If called as sh, does the same but with $ENV.
7627 */
7628 debug_printf("running script '%s'\n", argv[optind]);
7629 G.global_argv = argv + optind;
7630 G.global_argc = argc - optind;
7631 input = xfopen_for_read(argv[optind]);
7632 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007633 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007634 parse_and_run_file(input);
7635#if ENABLE_FEATURE_CLEAN_UP
7636 fclose(input);
7637#endif
7638 goto final_return;
7639 }
7640
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007641 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007642 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007643 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007644
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007645 /* A shell is interactive if the '-i' flag was given,
7646 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007647 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007648 * no arguments remaining or the -s flag given
7649 * standard input is a terminal
7650 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007651 * Refer to Posix.2, the description of the 'sh' utility.
7652 */
7653#if ENABLE_HUSH_JOB
7654 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007655 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7656 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7657 if (G_saved_tty_pgrp < 0)
7658 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007659
7660 /* try to dup stdin to high fd#, >= 255 */
7661 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7662 if (G_interactive_fd < 0) {
7663 /* try to dup to any fd */
7664 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007665 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007666 /* give up */
7667 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007668 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007669 }
7670 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007671// TODO: track & disallow any attempts of user
7672// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007673 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007674 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007675 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007676 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007677
Mike Frysinger38478a62009-05-20 04:48:06 -04007678 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007679 /* If we were run as 'hush &', sleep until we are
7680 * in the foreground (tty pgrp == our pgrp).
7681 * If we get started under a job aware app (like bash),
7682 * make sure we are now in charge so we don't fight over
7683 * who gets the foreground */
7684 while (1) {
7685 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007686 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7687 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007688 break;
7689 /* send TTIN to ourself (should stop us) */
7690 kill(- shell_pgrp, SIGTTIN);
7691 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007692 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007693
Denis Vlasenkof9375282009-04-05 19:13:39 +00007694 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007695 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007696
Mike Frysinger38478a62009-05-20 04:48:06 -04007697 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007698 /* Set other signals to restore saved_tty_pgrp */
7699 set_fatal_handlers();
7700 /* Put ourselves in our own process group
7701 * (bash, too, does this only if ctty is available) */
7702 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7703 /* Grab control of the terminal */
7704 tcsetpgrp(G_interactive_fd, getpid());
7705 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007706 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007707 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007708 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007709 } else {
7710 init_sigmasks();
7711 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007712#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007713 /* No job control compiled in, only prompt/line editing */
7714 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007715 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7716 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007717 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007718 G_interactive_fd = dup(STDIN_FILENO);
7719 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007720 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007721 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007722 }
7723 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007724 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007725 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007726 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007727 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007728#else
7729 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007730 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007731#endif
7732 /* bash:
7733 * if interactive but not a login shell, sources ~/.bashrc
7734 * (--norc turns this off, --rcfile <file> overrides)
7735 */
7736
7737 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007738 /* note: ash and hush share this string */
7739 printf("\n\n%s %s\n"
7740 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7741 "\n",
7742 bb_banner,
7743 "hush - the humble shell"
7744 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007745 }
7746
Denis Vlasenkof9375282009-04-05 19:13:39 +00007747 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007748
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007749 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007750#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007751 if (G.cwd != bb_msg_unknown)
7752 free((char*)G.cwd);
7753 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007754 while (cur_var) {
7755 struct variable *tmp = cur_var;
7756 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007757 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007758 cur_var = cur_var->next;
7759 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007760 }
Eric Andersen25f27032001-04-26 23:22:31 +00007761#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007762 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007763}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007764
7765
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007766#if ENABLE_MSH
7767int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7768int msh_main(int argc, char **argv)
7769{
7770 //bb_error_msg("msh is deprecated, please use hush instead");
7771 return hush_main(argc, argv);
7772}
7773#endif
7774
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007775
7776/*
7777 * Built-ins
7778 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007779static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007780{
7781 return 0;
7782}
7783
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007784static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007785{
7786 int argc = 0;
7787 while (*argv) {
7788 argc++;
7789 argv++;
7790 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007791 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007792}
7793
7794static int FAST_FUNC builtin_test(char **argv)
7795{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007796 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007797}
7798
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007799static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007800{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007801 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007802}
7803
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007804#if ENABLE_PRINTF
7805static int FAST_FUNC builtin_printf(char **argv)
7806{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007807 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007808}
7809#endif
7810
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007811static char **skip_dash_dash(char **argv)
7812{
7813 argv++;
7814 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7815 argv++;
7816 return argv;
7817}
7818
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007819static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007820{
7821 int rcode = EXIT_SUCCESS;
7822
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007823 argv = skip_dash_dash(argv);
7824 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007825 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007826 /* bash:
7827 * eval "echo Hi; done" ("done" is syntax error):
7828 * "echo Hi" will not execute too.
7829 */
7830 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007831 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007832 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007833 }
7834 return rcode;
7835}
7836
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007837static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007838{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007839 const char *newdir;
7840
7841 argv = skip_dash_dash(argv);
7842 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007843 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007844 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007845 * bash says "bash: cd: HOME not set" and does nothing
7846 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007847 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007848 const char *home = get_local_var_value("HOME");
7849 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007850 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007851 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007852 /* Mimic bash message exactly */
7853 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007854 return EXIT_FAILURE;
7855 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007856 /* Read current dir (get_cwd(1) is inside) and set PWD.
7857 * Note: do not enforce exporting. If PWD was unset or unexported,
7858 * set it again, but do not export. bash does the same.
7859 */
7860 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007861 return EXIT_SUCCESS;
7862}
7863
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007864static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007865{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007866 argv = skip_dash_dash(argv);
7867 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007868 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007869
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007870 /* Careful: we can end up here after [v]fork. Do not restore
7871 * tty pgrp then, only top-level shell process does that */
7872 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7873 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7874
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007875 /* TODO: if exec fails, bash does NOT exit! We do.
7876 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7877 * and tcsetpgrp, and this is inherently racy.
7878 */
7879 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007880}
7881
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007882static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007883{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007884 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007885
7886 /* interactive bash:
7887 * # trap "echo EEE" EXIT
7888 * # exit
7889 * exit
7890 * There are stopped jobs.
7891 * (if there are _stopped_ jobs, running ones don't count)
7892 * # exit
7893 * exit
7894 # EEE (then bash exits)
7895 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02007896 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00007897 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007898
7899 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007900 argv = skip_dash_dash(argv);
7901 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007902 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007903 /* mimic bash: exit 123abc == exit 255 + error msg */
7904 xfunc_error_retval = 255;
7905 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007906 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007907}
7908
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007909static void print_escaped(const char *s)
7910{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007911 if (*s == '\'')
7912 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007913 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007914 const char *p = strchrnul(s, '\'');
7915 /* print 'xxxx', possibly just '' */
7916 printf("'%.*s'", (int)(p - s), s);
7917 if (*p == '\0')
7918 break;
7919 s = p;
7920 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007921 /* s points to '; print "'''...'''" */
7922 putchar('"');
7923 do putchar('\''); while (*++s == '\'');
7924 putchar('"');
7925 } while (*s);
7926}
7927
Denys Vlasenko295fef82009-06-03 12:47:26 +02007928#if !ENABLE_HUSH_LOCAL
7929#define helper_export_local(argv, exp, lvl) \
7930 helper_export_local(argv, exp)
7931#endif
7932static void helper_export_local(char **argv, int exp, int lvl)
7933{
7934 do {
7935 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007936 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02007937
7938 /* So far we do not check that name is valid (TODO?) */
7939
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007940 if (*name_end == '\0') {
7941 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02007942
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007943 vpp = get_ptr_to_local_var(name, name_end - name);
7944 var = vpp ? *vpp : NULL;
7945
Denys Vlasenko295fef82009-06-03 12:47:26 +02007946 if (exp == -1) { /* unexporting? */
7947 /* export -n NAME (without =VALUE) */
7948 if (var) {
7949 var->flg_export = 0;
7950 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7951 unsetenv(name);
7952 } /* else: export -n NOT_EXISTING_VAR: no-op */
7953 continue;
7954 }
7955 if (exp == 1) { /* exporting? */
7956 /* export NAME (without =VALUE) */
7957 if (var) {
7958 var->flg_export = 1;
7959 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7960 putenv(var->varstr);
7961 continue;
7962 }
7963 }
7964 /* Exporting non-existing variable.
7965 * bash does not put it in environment,
7966 * but remembers that it is exported,
7967 * and does put it in env when it is set later.
7968 * We just set it to "" and export. */
7969 /* Or, it's "local NAME" (without =VALUE).
7970 * bash sets the value to "". */
7971 name = xasprintf("%s=", name);
7972 } else {
7973 /* (Un)exporting/making local NAME=VALUE */
7974 name = xstrdup(name);
7975 }
7976 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7977 } while (*++argv);
7978}
7979
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007980static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007981{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007982 unsigned opt_unexport;
7983
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007984#if ENABLE_HUSH_EXPORT_N
7985 /* "!": do not abort on errors */
7986 opt_unexport = getopt32(argv, "!n");
7987 if (opt_unexport == (uint32_t)-1)
7988 return EXIT_FAILURE;
7989 argv += optind;
7990#else
7991 opt_unexport = 0;
7992 argv++;
7993#endif
7994
7995 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007996 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007997 if (e) {
7998 while (*e) {
7999#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008000 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008001#else
8002 /* ash emits: export VAR='VAL'
8003 * bash: declare -x VAR="VAL"
8004 * we follow ash example */
8005 const char *s = *e++;
8006 const char *p = strchr(s, '=');
8007
8008 if (!p) /* wtf? take next variable */
8009 continue;
8010 /* export var= */
8011 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008012 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008013 putchar('\n');
8014#endif
8015 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008016 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008017 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008018 return EXIT_SUCCESS;
8019 }
8020
Denys Vlasenko295fef82009-06-03 12:47:26 +02008021 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008022
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008023 return EXIT_SUCCESS;
8024}
8025
Denys Vlasenko295fef82009-06-03 12:47:26 +02008026#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008027static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008028{
8029 if (G.func_nest_level == 0) {
8030 bb_error_msg("%s: not in a function", argv[0]);
8031 return EXIT_FAILURE; /* bash compat */
8032 }
8033 helper_export_local(argv, 0, G.func_nest_level);
8034 return EXIT_SUCCESS;
8035}
8036#endif
8037
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008038static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008039{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008040 int sig;
8041 char *new_cmd;
8042
8043 if (!G.traps)
8044 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8045
8046 argv++;
8047 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008048 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008049 /* No args: print all trapped */
8050 for (i = 0; i < NSIG; ++i) {
8051 if (G.traps[i]) {
8052 printf("trap -- ");
8053 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008054 /* note: bash adds "SIG", but only if invoked
8055 * as "bash". If called as "sh", or if set -o posix,
8056 * then it prints short signal names.
8057 * We are printing short names: */
8058 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008059 }
8060 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008061 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008062 return EXIT_SUCCESS;
8063 }
8064
8065 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008066 /* If first arg is a number: reset all specified signals */
8067 sig = bb_strtou(*argv, NULL, 10);
8068 if (errno == 0) {
8069 int ret;
8070 process_sig_list:
8071 ret = EXIT_SUCCESS;
8072 while (*argv) {
8073 sig = get_signum(*argv++);
8074 if (sig < 0 || sig >= NSIG) {
8075 ret = EXIT_FAILURE;
8076 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008077 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008078 continue;
8079 }
8080
8081 free(G.traps[sig]);
8082 G.traps[sig] = xstrdup(new_cmd);
8083
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008084 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008085 get_signame(sig), sig, G.traps[sig]);
8086
8087 /* There is no signal for 0 (EXIT) */
8088 if (sig == 0)
8089 continue;
8090
8091 if (new_cmd) {
8092 sigaddset(&G.blocked_set, sig);
8093 } else {
8094 /* There was a trap handler, we are removing it
8095 * (if sig has non-DFL handling,
8096 * we don't need to do anything) */
8097 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8098 continue;
8099 sigdelset(&G.blocked_set, sig);
8100 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008101 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008102 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008103 return ret;
8104 }
8105
8106 if (!argv[1]) { /* no second arg */
8107 bb_error_msg("trap: invalid arguments");
8108 return EXIT_FAILURE;
8109 }
8110
8111 /* First arg is "-": reset all specified to default */
8112 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8113 /* Everything else: set arg as signal handler
8114 * (includes "" case, which ignores signal) */
8115 if (argv[0][0] == '-') {
8116 if (argv[0][1] == '\0') { /* "-" */
8117 /* new_cmd remains NULL: "reset these sigs" */
8118 goto reset_traps;
8119 }
8120 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8121 argv++;
8122 }
8123 /* else: "-something", no special meaning */
8124 }
8125 new_cmd = *argv;
8126 reset_traps:
8127 argv++;
8128 goto process_sig_list;
8129}
8130
Mike Frysinger93cadc22009-05-27 17:06:25 -04008131/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008132static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008133{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008134 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008135
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008136 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008137 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008138 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008139
8140 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008141 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008142 type = "an alias";*/
8143#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008144 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008145 type = "a function";
8146#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008147 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008148 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008149 else if ((path = find_in_path(*argv)) != NULL)
8150 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008151 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008152 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008153 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008154 continue;
8155 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008156
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008157 printf("%s is %s\n", *argv, type);
8158 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008159 }
8160
8161 return ret;
8162}
8163
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008164#if ENABLE_HUSH_JOB
8165/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008166static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008167{
8168 int i, jobnum;
8169 struct pipe *pi;
8170
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008171 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008172 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008173
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008174 /* If they gave us no args, assume they want the last backgrounded task */
8175 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008176 for (pi = G.job_list; pi; pi = pi->next) {
8177 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008178 goto found;
8179 }
8180 }
8181 bb_error_msg("%s: no current job", argv[0]);
8182 return EXIT_FAILURE;
8183 }
8184 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8185 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8186 return EXIT_FAILURE;
8187 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008188 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008189 if (pi->jobid == jobnum) {
8190 goto found;
8191 }
8192 }
8193 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8194 return EXIT_FAILURE;
8195 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008196 /* TODO: bash prints a string representation
8197 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008198 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008199 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008200 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008201 }
8202
8203 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008204 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8205 for (i = 0; i < pi->num_cmds; i++) {
8206 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8207 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008208 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008209 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008210
8211 i = kill(- pi->pgrp, SIGCONT);
8212 if (i < 0) {
8213 if (errno == ESRCH) {
8214 delete_finished_bg_job(pi);
8215 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008216 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008217 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008218 }
8219
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008220 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008221 remove_bg_job(pi);
8222 return checkjobs_and_fg_shell(pi);
8223 }
8224 return EXIT_SUCCESS;
8225}
8226#endif
8227
8228#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008229static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008230{
8231 const struct built_in_command *x;
8232
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008233 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008234 "Built-in commands:\n"
8235 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008236 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008237 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008238 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008239 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008240 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008241 return EXIT_SUCCESS;
8242}
8243#endif
8244
8245#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008246static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008247{
8248 struct pipe *job;
8249 const char *status_string;
8250
Denis Vlasenko87a86552008-07-29 19:43:10 +00008251 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008252 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008253 status_string = "Stopped";
8254 else
8255 status_string = "Running";
8256
8257 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8258 }
8259 return EXIT_SUCCESS;
8260}
8261#endif
8262
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008263#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008264static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008265{
8266 void *p;
8267 unsigned long l;
8268
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008269# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008270 /* Optional. Reduces probability of false positives */
8271 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008272# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008273 /* Crude attempt to find where "free memory" starts,
8274 * sans fragmentation. */
8275 p = malloc(240);
8276 l = (unsigned long)p;
8277 free(p);
8278 p = malloc(3400);
8279 if (l < (unsigned long)p) l = (unsigned long)p;
8280 free(p);
8281
8282 if (!G.memleak_value)
8283 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008284
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008285 l -= G.memleak_value;
8286 if ((long)l < 0)
8287 l = 0;
8288 l /= 1024;
8289 if (l > 127)
8290 l = 127;
8291
8292 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8293 return l;
8294}
8295#endif
8296
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008297static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008298{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008299 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008300 return EXIT_SUCCESS;
8301}
8302
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008303static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008304{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008305 const char *r;
8306 char *opt_n = NULL;
8307 char *opt_p = NULL;
8308 char *opt_t = NULL;
8309 char *opt_u = NULL;
8310 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008311
Denys Vlasenko03dad222010-01-12 23:29:57 +01008312 /* "!": do not abort on errors.
8313 * Option string must start with "sr" to match BUILTIN_READ_xxx
8314 */
8315 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8316 if (read_flags == (uint32_t)-1)
8317 return EXIT_FAILURE;
8318 argv += optind;
8319
8320 r = shell_builtin_read(set_local_var_from_halves,
8321 argv,
8322 get_local_var_value("IFS"), /* can be NULL */
8323 read_flags,
8324 opt_n,
8325 opt_p,
8326 opt_t,
8327 opt_u
8328 );
8329
8330 if ((uintptr_t)r > 1) {
8331 bb_error_msg("%s", r);
8332 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008333 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008334
Denys Vlasenko03dad222010-01-12 23:29:57 +01008335 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008336}
8337
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008338/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8339 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008340 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008341 * set [-abCefhmnuvx] [-o option] [argument...]
8342 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008343 * set -- [argument...]
8344 * set -o
8345 * set +o
8346 * Implementations shall support the options in both their hyphen and
8347 * plus-sign forms. These options can also be specified as options to sh.
8348 * Examples:
8349 * Write out all variables and their values: set
8350 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8351 * Turn on the -x and -v options: set -xv
8352 * Unset all positional parameters: set --
8353 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8354 * Set the positional parameters to the expansion of x, even if x expands
8355 * with a leading '-' or '+': set -- $x
8356 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008357 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008358 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008359static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008360{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008361 int n;
8362 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008363 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008364
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008365 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008366 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008367 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008368 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008369 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008370 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008371
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008372 do {
8373 if (!strcmp(arg, "--")) {
8374 ++argv;
8375 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008376 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008377 if (arg[0] != '+' && arg[0] != '-')
8378 break;
8379 for (n = 1; arg[n]; ++n)
8380 if (set_mode(arg[0], arg[n]))
8381 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008382 } while ((arg = *++argv) != NULL);
8383 /* Now argv[0] is 1st argument */
8384
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008385 if (arg == NULL)
8386 return EXIT_SUCCESS;
8387 set_argv:
8388
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008389 /* NB: G.global_argv[0] ($0) is never freed/changed */
8390 g_argv = G.global_argv;
8391 if (G.global_args_malloced) {
8392 pp = g_argv;
8393 while (*++pp)
8394 free(*pp);
8395 g_argv[1] = NULL;
8396 } else {
8397 G.global_args_malloced = 1;
8398 pp = xzalloc(sizeof(pp[0]) * 2);
8399 pp[0] = g_argv[0]; /* retain $0 */
8400 g_argv = pp;
8401 }
8402 /* This realloc's G.global_argv */
8403 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8404
8405 n = 1;
8406 while (*++pp)
8407 n++;
8408 G.global_argc = n;
8409
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008410 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008411
8412 /* Nothing known, so abort */
8413 error:
8414 bb_error_msg("set: %s: invalid option", arg);
8415 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008416}
8417
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008418static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008419{
8420 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008421 argv = skip_dash_dash(argv);
8422 if (argv[0]) {
8423 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008424 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008425 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008426 if (G.global_args_malloced) {
8427 int m = 1;
8428 while (m <= n)
8429 free(G.global_argv[m++]);
8430 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008431 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008432 memmove(&G.global_argv[1], &G.global_argv[n+1],
8433 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008434 return EXIT_SUCCESS;
8435 }
8436 return EXIT_FAILURE;
8437}
8438
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008439static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008440{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008441 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008442 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008443 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008444#if ENABLE_HUSH_FUNCTIONS
8445 smallint sv_flg;
8446#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008447
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008448 argv = skip_dash_dash(argv);
8449 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008450 if (!filename) {
8451 /* bash says: "bash: .: filename argument required" */
8452 return 2; /* bash compat */
8453 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008454 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008455 if (!strchr(filename, '/')) {
8456 arg_path = find_in_path(filename);
8457 if (arg_path)
8458 filename = arg_path;
8459 }
8460 input = fopen_or_warn(filename, "r");
8461 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008462 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008463 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008464 return EXIT_FAILURE;
8465 }
8466 close_on_exec_on(fileno(input));
8467
Mike Frysinger885b6f22009-04-18 21:04:25 +00008468#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008469 sv_flg = G.flag_return_in_progress;
8470 /* "we are inside sourced file, ok to use return" */
8471 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008472#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008473 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008474
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008475 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008476 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008477
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008478 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008479#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008480 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008481#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008482
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008483 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008484}
8485
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008486static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008487{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008488 int rc;
8489 mode_t mask;
8490
8491 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008492 argv = skip_dash_dash(argv);
8493 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008494 mode_t old_mask = mask;
8495
8496 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008497 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008498 mask ^= 0777;
8499 if (rc == 0) {
8500 mask = old_mask;
8501 /* bash messages:
8502 * bash: umask: 'q': invalid symbolic mode operator
8503 * bash: umask: 999: octal number out of range
8504 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008505 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008506 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008507 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008508 rc = 1;
8509 /* Mimic bash */
8510 printf("%04o\n", (unsigned) mask);
8511 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008512 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008513 umask(mask);
8514
8515 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008516}
8517
Mike Frysingerd690f682009-03-30 06:50:54 +00008518/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008519static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008520{
Mike Frysingerd690f682009-03-30 06:50:54 +00008521 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008522 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008523
Denis Vlasenko28e67962009-04-26 23:22:40 +00008524 /* "!": do not abort on errors */
8525 /* "+": stop at 1st non-option */
8526 opts = getopt32(argv, "!+vf");
8527 if (opts == (unsigned)-1)
8528 return EXIT_FAILURE;
8529 if (opts == 3) {
8530 bb_error_msg("unset: -v and -f are exclusive");
8531 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008532 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008533 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008534
8535 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008536 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008537 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008538 if (unset_local_var(*argv)) {
8539 /* unset <nonexistent_var> doesn't fail.
8540 * Error is when one tries to unset RO var.
8541 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008542 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008543 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008544 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008545#if ENABLE_HUSH_FUNCTIONS
8546 else {
8547 unset_func(*argv);
8548 }
8549#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008550 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008551 }
8552 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008553}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008554
Mike Frysinger56bdea12009-03-28 20:01:58 +00008555/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008556static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008557{
8558 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008559 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008560
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008561 argv = skip_dash_dash(argv);
8562 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008563 /* Don't care about wait results */
8564 /* Note 1: must wait until there are no more children */
8565 /* Note 2: must be interruptible */
8566 /* Examples:
8567 * $ sleep 3 & sleep 6 & wait
8568 * [1] 30934 sleep 3
8569 * [2] 30935 sleep 6
8570 * [1] Done sleep 3
8571 * [2] Done sleep 6
8572 * $ sleep 3 & sleep 6 & wait
8573 * [1] 30936 sleep 3
8574 * [2] 30937 sleep 6
8575 * [1] Done sleep 3
8576 * ^C <-- after ~4 sec from keyboard
8577 * $
8578 */
8579 sigaddset(&G.blocked_set, SIGCHLD);
8580 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8581 while (1) {
8582 checkjobs(NULL);
8583 if (errno == ECHILD)
8584 break;
8585 /* Wait for SIGCHLD or any other signal of interest */
8586 /* sigtimedwait with infinite timeout: */
8587 sig = sigwaitinfo(&G.blocked_set, NULL);
8588 if (sig > 0) {
8589 sig = check_and_run_traps(sig);
8590 if (sig && sig != SIGCHLD) { /* see note 2 */
8591 ret = 128 + sig;
8592 break;
8593 }
8594 }
8595 }
8596 sigdelset(&G.blocked_set, SIGCHLD);
8597 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8598 return ret;
8599 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008600
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008601 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008602 while (*argv) {
8603 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008604 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008605 /* mimic bash message */
8606 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008607 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008608 }
8609 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008610 if (WIFSIGNALED(status))
8611 ret = 128 + WTERMSIG(status);
8612 else if (WIFEXITED(status))
8613 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008614 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008615 ret = EXIT_FAILURE;
8616 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008617 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008618 ret = 127;
8619 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008620 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008621 }
8622
8623 return ret;
8624}
8625
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008626#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8627static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8628{
8629 if (argv[1]) {
8630 def = bb_strtou(argv[1], NULL, 10);
8631 if (errno || def < def_min || argv[2]) {
8632 bb_error_msg("%s: bad arguments", argv[0]);
8633 def = UINT_MAX;
8634 }
8635 }
8636 return def;
8637}
8638#endif
8639
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008640#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008641static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008642{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008643 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008644 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008645 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008646 return EXIT_SUCCESS; /* bash compat */
8647 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008648 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008649
8650 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8651 if (depth == UINT_MAX)
8652 G.flag_break_continue = BC_BREAK;
8653 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008654 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008655
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008656 return EXIT_SUCCESS;
8657}
8658
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008659static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008660{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008661 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8662 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008663}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008664#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008665
8666#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008667static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008668{
8669 int rc;
8670
8671 if (G.flag_return_in_progress != -1) {
8672 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8673 return EXIT_FAILURE; /* bash compat */
8674 }
8675
8676 G.flag_return_in_progress = 1;
8677
8678 /* bash:
8679 * out of range: wraps around at 256, does not error out
8680 * non-numeric param:
8681 * f() { false; return qwe; }; f; echo $?
8682 * bash: return: qwe: numeric argument required <== we do this
8683 * 255 <== we also do this
8684 */
8685 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8686 return rc;
8687}
8688#endif