blob: 2a4e80b6ea26ad7584748e02b4ef18d70e0319ca [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:
132//config:config HUSH_HELP
133//config: bool "help builtin"
134//config: default y
135//config: depends on HUSH
136//config: help
137//config: Enable help builtin in hush. Code size + ~1 kbyte.
138//config:
139//config:config HUSH_INTERACTIVE
140//config: bool "Interactive mode"
141//config: default y
142//config: depends on HUSH
143//config: help
144//config: Enable interactive mode (prompt and command editing).
145//config: Without this, hush simply reads and executes commands
146//config: from stdin just like a shell script from a file.
147//config: No prompt, no PS1/PS2 magic shell variables.
148//config:
149//config:config HUSH_JOB
150//config: bool "Job control"
151//config: default y
152//config: depends on HUSH_INTERACTIVE
153//config: help
154//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
155//config: command (not entire shell), fg/bg builtins work. Without this option,
156//config: "cmd &" still works by simply spawning a process and immediately
157//config: prompting for next command (or executing next command in a script),
158//config: but no separate process group is formed.
159//config:
160//config:config HUSH_TICK
161//config: bool "Process substitution"
162//config: default y
163//config: depends on HUSH
164//config: help
165//config: Enable process substitution `command` and $(command) in hush.
166//config:
167//config:config HUSH_IF
168//config: bool "Support if/then/elif/else/fi"
169//config: default y
170//config: depends on HUSH
171//config: help
172//config: Enable if/then/elif/else/fi in hush.
173//config:
174//config:config HUSH_LOOPS
175//config: bool "Support for, while and until loops"
176//config: default y
177//config: depends on HUSH
178//config: help
179//config: Enable for, while and until loops in hush.
180//config:
181//config:config HUSH_CASE
182//config: bool "Support case ... esac statement"
183//config: default y
184//config: depends on HUSH
185//config: help
186//config: Enable case ... esac statement in hush. +400 bytes.
187//config:
188//config:config HUSH_FUNCTIONS
189//config: bool "Support funcname() { commands; } syntax"
190//config: default y
191//config: depends on HUSH
192//config: help
193//config: Enable support for shell functions in hush. +800 bytes.
194//config:
195//config:config HUSH_LOCAL
196//config: bool "Support local builtin"
197//config: default y
198//config: depends on HUSH_FUNCTIONS
199//config: help
200//config: Enable support for local variables in functions.
201//config:
202//config:config HUSH_RANDOM_SUPPORT
203//config: bool "Pseudorandom generator and $RANDOM variable"
204//config: default y
205//config: depends on HUSH
206//config: help
207//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
208//config: Each read of "$RANDOM" will generate a new pseudorandom value.
209//config:
210//config:config HUSH_EXPORT_N
211//config: bool "Support 'export -n' option"
212//config: default y
213//config: depends on HUSH
214//config: help
215//config: export -n unexports variables. It is a bash extension.
216//config:
217//config:config HUSH_MODE_X
218//config: bool "Support 'hush -x' option and 'set -x' command"
219//config: default y
220//config: depends on HUSH
221//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200222//config: This instructs hush to print commands before execution.
223//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200224//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200225//config:config MSH
226//config: bool "msh (deprecated: aliased to hush)"
227//config: default n
228//config: select HUSH
229//config: help
230//config: msh is deprecated and will be removed, please migrate to hush.
231//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200232
233//usage:#define hush_trivial_usage NOUSAGE_STR
234//usage:#define hush_full_usage ""
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200235//usage:#define msh_trivial_usage NOUSAGE_STR
236//usage:#define msh_full_usage ""
237
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000238
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200239/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000240#define LEAK_HUNTING 0
241#define BUILD_AS_NOMMU 0
242/* Enable/disable sanity checks. Ok to enable in production,
243 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
244 * Keeping 1 for now even in released versions.
245 */
246#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200247/* Slightly bigger (+200 bytes), but faster hush.
248 * So far it only enables a trick with counting SIGCHLDs and forks,
249 * which allows us to do fewer waitpid's.
250 * (we can detect a case where neither forks were done nor SIGCHLDs happened
251 * and therefore waitpid will return the same result as last time)
252 */
253#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200254/* TODO: implement simplified code for users which do not need ${var%...} ops
255 * So far ${var%...} ops are always enabled:
256 */
257#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000258
259
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000260#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000261# undef BB_MMU
262# undef USE_FOR_NOMMU
263# undef USE_FOR_MMU
264# define BB_MMU 0
265# define USE_FOR_NOMMU(...) __VA_ARGS__
266# define USE_FOR_MMU(...)
267#endif
268
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200269#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100270#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000271/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000272# undef CONFIG_FEATURE_SH_STANDALONE
273# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000274# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100275# undef IF_NOT_FEATURE_SH_STANDALONE
276# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000277# define IF_FEATURE_SH_STANDALONE(...)
278# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000279#endif
280
Denis Vlasenko05743d72008-02-10 12:10:08 +0000281#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000282# undef ENABLE_FEATURE_EDITING
283# define ENABLE_FEATURE_EDITING 0
284# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
285# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000286#endif
287
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000288/* Do we support ANY keywords? */
289#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000290# define HAS_KEYWORDS 1
291# define IF_HAS_KEYWORDS(...) __VA_ARGS__
292# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000293#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000294# define HAS_KEYWORDS 0
295# define IF_HAS_KEYWORDS(...)
296# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000297#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000298
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000299/* If you comment out one of these below, it will be #defined later
300 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000301#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000302/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000303#define debug_printf_parse(...) do {} while (0)
304#define debug_print_tree(a, b) do {} while (0)
305#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000306#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000307#define debug_printf_jobs(...) do {} while (0)
308#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200309#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000310#define debug_printf_glob(...) do {} while (0)
311#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000312#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000313#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000314
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000315#define ERR_PTR ((void*)(long)1)
316
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200317#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000318
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200319#define _SPECIAL_VARS_STR "_*@$!?#"
320#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
321#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200322#if ENABLE_HUSH_BASH_COMPAT
323/* Support / and // replace ops */
324/* Note that // is stored as \ in "encoded" string representation */
325# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
326# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
327# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
328#else
329# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
330# define VAR_SUBST_OPS "%#:-=+?"
331# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
332#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200333
334#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000335
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200336struct variable;
337
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000338static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
339
340/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000341 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000342 */
343#if !BB_MMU
344typedef struct nommu_save_t {
345 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200346 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000347 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000348 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000349} nommu_save_t;
350#endif
351
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000352typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000353 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000354#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000355 RES_IF ,
356 RES_THEN ,
357 RES_ELIF ,
358 RES_ELSE ,
359 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000360#endif
361#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000362 RES_FOR ,
363 RES_WHILE ,
364 RES_UNTIL ,
365 RES_DO ,
366 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000367#endif
368#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000369 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000370#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000371#if ENABLE_HUSH_CASE
372 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200373 /* three pseudo-keywords support contrived "case" syntax: */
374 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
375 RES_MATCH , /* "word)" */
376 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000377 RES_ESAC ,
378#endif
379 RES_XXXX ,
380 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000381} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000382
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000383typedef struct o_string {
384 char *data;
385 int length; /* position where data is appended */
386 int maxlen;
387 /* Protect newly added chars against globbing
388 * (by prepending \ to *, ?, [, \) */
389 smallint o_escape;
390 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000391 /* At least some part of the string was inside '' or "",
392 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200393 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000394 smallint has_empty_slot;
395 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
396} o_string;
397enum {
398 MAYBE_ASSIGNMENT = 0,
399 DEFINITELY_ASSIGNMENT = 1,
400 NOT_ASSIGNMENT = 2,
401 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
402};
403/* Used for initialization: o_string foo = NULL_O_STRING; */
404#define NULL_O_STRING { NULL }
405
406/* I can almost use ordinary FILE*. Is open_memstream() universally
407 * available? Where is it documented? */
408typedef struct in_str {
409 const char *p;
410 /* eof_flag=1: last char in ->p is really an EOF */
411 char eof_flag; /* meaningless if ->p == NULL */
412 char peek_buf[2];
413#if ENABLE_HUSH_INTERACTIVE
414 smallint promptme;
415 smallint promptmode; /* 0: PS1, 1: PS2 */
416#endif
417 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200418 int (*get) (struct in_str *) FAST_FUNC;
419 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000420} in_str;
421#define i_getch(input) ((input)->get(input))
422#define i_peek(input) ((input)->peek(input))
423
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200424/* The descrip member of this structure is only used to make
425 * debugging output pretty */
426static const struct {
427 int mode;
428 signed char default_fd;
429 char descrip[3];
430} redir_table[] = {
431 { O_RDONLY, 0, "<" },
432 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
433 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
434 { O_CREAT|O_RDWR, 1, "<>" },
435 { O_RDONLY, 0, "<<" },
436/* Should not be needed. Bogus default_fd helps in debugging */
437/* { O_RDONLY, 77, "<<" }, */
438};
439
Eric Andersen25f27032001-04-26 23:22:31 +0000440struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000441 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000442 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000443 int rd_fd; /* fd to redirect */
444 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
445 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000446 smallint rd_type; /* (enum redir_type) */
447 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000448 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200449 * bit 0: do we need to trim leading tabs?
450 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000451 */
Eric Andersen25f27032001-04-26 23:22:31 +0000452};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000453typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200454 REDIRECT_INPUT = 0,
455 REDIRECT_OVERWRITE = 1,
456 REDIRECT_APPEND = 2,
457 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000458 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200459 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000460
461 REDIRFD_CLOSE = -3,
462 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000463 REDIRFD_TO_FILE = -1,
464 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000465
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000466 HEREDOC_SKIPTABS = 1,
467 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000468} redir_type;
469
Eric Andersen25f27032001-04-26 23:22:31 +0000470
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000471struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000472 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000473 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000474 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200475 smallint cmd_type; /* CMD_xxx */
476#define CMD_NORMAL 0
477#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200478#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200479/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200480# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000481#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200482#if ENABLE_HUSH_FUNCTIONS
483# define CMD_FUNCDEF 3
484#endif
485
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200486 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
487 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000488#if !BB_MMU
489 char *group_as_string;
490#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000491#if ENABLE_HUSH_FUNCTIONS
492 struct function *child_func;
493/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200494 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000495 * When we execute "f1() {a;}" cmd, we create new function and clear
496 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200497 * When we execute "f1() {b;}", we notice that f1 exists,
498 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000499 * we put those fields back into cmd->xxx
500 * (struct function has ->parent_cmd ptr to facilitate that).
501 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
502 * Without this trick, loop would execute a;b;b;b;...
503 * instead of correct sequence a;b;a;b;...
504 * When command is freed, it severs the link
505 * (sets ->child_func->parent_cmd to NULL).
506 */
507#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000508 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000509/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
510 * and on execution these are substituted with their values.
511 * Substitution can make _several_ words out of one argv[n]!
512 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000513 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000514 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000515 struct redir_struct *redirects; /* I/O redirections */
516};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000517/* Is there anything in this command at all? */
518#define IS_NULL_CMD(cmd) \
519 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
520
Eric Andersen25f27032001-04-26 23:22:31 +0000521
522struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000523 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000524 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000525 int alive_cmds; /* number of commands running (not exited) */
526 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000527#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000528 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000529 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000530 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000531#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000532 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000533 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000534 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
535 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000536};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000537typedef enum pipe_style {
538 PIPE_SEQ = 1,
539 PIPE_AND = 2,
540 PIPE_OR = 3,
541 PIPE_BG = 4,
542} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000543/* Is there anything in this pipe at all? */
544#define IS_NULL_PIPE(pi) \
545 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000546
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000547/* This holds pointers to the various results of parsing */
548struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000549 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000550 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000551 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000552 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000553 /* last command in pipe (being constructed right now) */
554 struct command *command;
555 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000556 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000557#if !BB_MMU
558 o_string as_string;
559#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000560#if HAS_KEYWORDS
561 smallint ctx_res_w;
562 smallint ctx_inverted; /* "! cmd | cmd" */
563#if ENABLE_HUSH_CASE
564 smallint ctx_dsemicolon; /* ";;" seen */
565#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000566 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
567 int old_flag;
568 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000569 * example: "if pipe1; pipe2; then pipe3; fi"
570 * when we see "if" or "then", we malloc and copy current context,
571 * and make ->stack point to it. then we parse pipeN.
572 * when closing "then" / fi" / whatever is found,
573 * we move list_head into ->stack->command->group,
574 * copy ->stack into current context, and delete ->stack.
575 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000576 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000577 struct parse_context *stack;
578#endif
579};
580
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000581/* On program start, environ points to initial environment.
582 * putenv adds new pointers into it, unsetenv removes them.
583 * Neither of these (de)allocates the strings.
584 * setenv allocates new strings in malloc space and does putenv,
585 * and thus setenv is unusable (leaky) for shell's purposes */
586#define setenv(...) setenv_is_leaky_dont_use()
587struct variable {
588 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000589 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200590#if ENABLE_HUSH_LOCAL
591 unsigned func_nest_level;
592#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000593 int max_len; /* if > 0, name is part of initial env; else name is malloced */
594 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000595 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000596};
597
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000598enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000599 BC_BREAK = 1,
600 BC_CONTINUE = 2,
601};
602
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000603#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000604struct function {
605 struct function *next;
606 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000607 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000608 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200609# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000610 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200611# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000612};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000613#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000614
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000615
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000616/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000617/* Sorted roughly by size (smaller offsets == smaller code) */
618struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000619 /* interactive_fd != 0 means we are an interactive shell.
620 * If we are, then saved_tty_pgrp can also be != 0, meaning
621 * that controlling tty is available. With saved_tty_pgrp == 0,
622 * job control still works, but terminal signals
623 * (^C, ^Z, ^Y, ^\) won't work at all, and background
624 * process groups can only be created with "cmd &".
625 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
626 * to give tty to the foreground process group,
627 * and will take it back when the group is stopped (^Z)
628 * or killed (^C).
629 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000630#if ENABLE_HUSH_INTERACTIVE
631 /* 'interactive_fd' is a fd# open to ctty, if we have one
632 * _AND_ if we decided to act interactively */
633 int interactive_fd;
634 const char *PS1;
635 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000636# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000637#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000638# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000639#endif
640#if ENABLE_FEATURE_EDITING
641 line_input_t *line_input_state;
642#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000643 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200644 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000645 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200646#if ENABLE_HUSH_RANDOM_SUPPORT
647 random_t random_gen;
648#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000649#if ENABLE_HUSH_JOB
650 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000651 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000652 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000653 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400654# define G_saved_tty_pgrp (G.saved_tty_pgrp)
655#else
656# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000657#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000658 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000659#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000660 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000661#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000662#if ENABLE_HUSH_FUNCTIONS
663 /* 0: outside of a function (or sourced file)
664 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000665 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000666 */
667 smallint flag_return_in_progress;
668#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200669 smallint n_mode;
670#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200671 smallint x_mode;
Denys Vlasenko29082232010-07-16 13:52:32 +0200672# define G_x_mode (G.x_mode)
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200673#else
674# define G_x_mode 0
675#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000676 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000677 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000678 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000679 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000680 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100681 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000682 /* how many non-NULL argv's we have. NB: $# + 1 */
683 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000684 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000685#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000686 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000687#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000688#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000689 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000690 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000691#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000692 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000693 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000694 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000695 struct variable shell_ver;
Denys Vlasenko29082232010-07-16 13:52:32 +0200696 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000697#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000698 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200699# if ENABLE_HUSH_LOCAL
700 struct variable **shadowed_vars_pp;
701 unsigned func_nest_level;
702# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000703#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000704 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200705#if ENABLE_HUSH_FAST
706 unsigned count_SIGCHLD;
707 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200708 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200709#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000710 /* which signals have non-DFL handler (even with no traps set)? */
711 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000712 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000713 sigset_t blocked_set;
714 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000715#if HUSH_DEBUG
716 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000717 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000718#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200719 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000720};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000721#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000722/* Not #defining name to G.name - this quickly gets unwieldy
723 * (too many defines). Also, I actually prefer to see when a variable
724 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000725#define INIT_G() do { \
726 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
727} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000728
729
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000730/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200731static int builtin_cd(char **argv) FAST_FUNC;
732static int builtin_echo(char **argv) FAST_FUNC;
733static int builtin_eval(char **argv) FAST_FUNC;
734static int builtin_exec(char **argv) FAST_FUNC;
735static int builtin_exit(char **argv) FAST_FUNC;
736static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000737#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200738static int builtin_fg_bg(char **argv) FAST_FUNC;
739static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000740#endif
741#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200742static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000743#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200744#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200745static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200746#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000747#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200748static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000749#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400750#if ENABLE_PRINTF
751static int builtin_printf(char **argv) FAST_FUNC;
752#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200753static int builtin_pwd(char **argv) FAST_FUNC;
754static int builtin_read(char **argv) FAST_FUNC;
755static int builtin_set(char **argv) FAST_FUNC;
756static int builtin_shift(char **argv) FAST_FUNC;
757static int builtin_source(char **argv) FAST_FUNC;
758static int builtin_test(char **argv) FAST_FUNC;
759static int builtin_trap(char **argv) FAST_FUNC;
760static int builtin_type(char **argv) FAST_FUNC;
761static int builtin_true(char **argv) FAST_FUNC;
762static int builtin_umask(char **argv) FAST_FUNC;
763static int builtin_unset(char **argv) FAST_FUNC;
764static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000765#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200766static int builtin_break(char **argv) FAST_FUNC;
767static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000768#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000769#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200770static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000771#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000772
773/* Table of built-in functions. They can be forked or not, depending on
774 * context: within pipes, they fork. As simple commands, they do not.
775 * When used in non-forking context, they can change global variables
776 * in the parent shell process. If forked, of course they cannot.
777 * For example, 'unset foo | whatever' will parse and run, but foo will
778 * still be set at the end. */
779struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100780 const char *b_cmd;
781 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000782#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100783 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200784# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000785#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200786# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000787#endif
788};
789
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200790static const struct built_in_command bltins1[] = {
791 BLTIN("." , builtin_source , "Run commands in a file"),
792 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000793#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200794 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000795#endif
796#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200797 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000798#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200799 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000800#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200801 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000802#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200803 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
804 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
805 BLTIN("exit" , builtin_exit , "Exit"),
806 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000807#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200808 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000809#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000810#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200811 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000812#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000813#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200814 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000815#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200816#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200817 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200818#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000819#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200820 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000821#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200822 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000823#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200824 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000825#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200826 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
827 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200828#if ENABLE_HUSH_BASH_COMPAT
829 BLTIN("source" , builtin_source , "Run commands in a file"),
830#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200831 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100832 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100833 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200834 BLTIN("umask" , builtin_umask , "Set file creation mask"),
835 BLTIN("unset" , builtin_unset , "Unset variables"),
836 BLTIN("wait" , builtin_wait , "Wait for process"),
837};
838/* For now, echo and test are unconditionally enabled.
839 * Maybe make it configurable? */
840static const struct built_in_command bltins2[] = {
841 BLTIN("[" , builtin_test , NULL),
842 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400843#if ENABLE_PRINTF
844 BLTIN("printf" , builtin_printf , NULL),
845#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200846 BLTIN("pwd" , builtin_pwd , NULL),
847 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000848};
849
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000851/* Debug printouts.
852 */
853#if HUSH_DEBUG
854/* prevent disasters with G.debug_indent < 0 */
855# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
856# define debug_enter() (G.debug_indent++)
857# define debug_leave() (G.debug_indent--)
858#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200859# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000860# define debug_enter() ((void)0)
861# define debug_leave() ((void)0)
862#endif
863
864#ifndef debug_printf
865# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
866#endif
867
868#ifndef debug_printf_parse
869# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
870#endif
871
872#ifndef debug_printf_exec
873#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
874#endif
875
876#ifndef debug_printf_env
877# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
878#endif
879
880#ifndef debug_printf_jobs
881# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
882# define DEBUG_JOBS 1
883#else
884# define DEBUG_JOBS 0
885#endif
886
887#ifndef debug_printf_expand
888# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
889# define DEBUG_EXPAND 1
890#else
891# define DEBUG_EXPAND 0
892#endif
893
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200894#ifndef debug_printf_varexp
895# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
896#endif
897
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000898#ifndef debug_printf_glob
899# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
900# define DEBUG_GLOB 1
901#else
902# define DEBUG_GLOB 0
903#endif
904
905#ifndef debug_printf_list
906# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
907#endif
908
909#ifndef debug_printf_subst
910# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
911#endif
912
913#ifndef debug_printf_clean
914# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
915# define DEBUG_CLEAN 1
916#else
917# define DEBUG_CLEAN 0
918#endif
919
920#if DEBUG_EXPAND
921static void debug_print_strings(const char *prefix, char **vv)
922{
923 indent();
924 fprintf(stderr, "%s:\n", prefix);
925 while (*vv)
926 fprintf(stderr, " '%s'\n", *vv++);
927}
928#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200929# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000930#endif
931
932
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000933/* Leak hunting. Use hush_leaktool.sh for post-processing.
934 */
935#if LEAK_HUNTING
936static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000937{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000938 void *ptr = xmalloc((size + 0xff) & ~0xff);
939 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
940 return ptr;
941}
942static void *xxrealloc(int lineno, void *ptr, size_t size)
943{
944 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
945 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
946 return ptr;
947}
948static char *xxstrdup(int lineno, const char *str)
949{
950 char *ptr = xstrdup(str);
951 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
952 return ptr;
953}
954static void xxfree(void *ptr)
955{
956 fdprintf(2, "free %p\n", ptr);
957 free(ptr);
958}
Denys Vlasenko8391c482010-05-22 17:50:43 +0200959# define xmalloc(s) xxmalloc(__LINE__, s)
960# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
961# define xstrdup(s) xxstrdup(__LINE__, s)
962# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000963#endif
964
965
966/* Syntax and runtime errors. They always abort scripts.
967 * In interactive use they usually discard unparsed and/or unexecuted commands
968 * and return to the prompt.
969 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
970 */
971#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200972# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000973# define syntax_error(lineno, msg) syntax_error(msg)
974# define syntax_error_at(lineno, msg) syntax_error_at(msg)
975# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
976# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
977# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000978#endif
979
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000980static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000981{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000982 va_list p;
983
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000984#if HUSH_DEBUG >= 2
985 bb_error_msg("hush.c:%u", lineno);
986#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000987 va_start(p, fmt);
988 bb_verror_msg(fmt, p, NULL);
989 va_end(p);
990 if (!G_interactive_fd)
991 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000992}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000993
994static void syntax_error(unsigned lineno, const char *msg)
995{
996 if (msg)
997 die_if_script(lineno, "syntax error: %s", msg);
998 else
999 die_if_script(lineno, "syntax error", NULL);
1000}
1001
1002static void syntax_error_at(unsigned lineno, const char *msg)
1003{
1004 die_if_script(lineno, "syntax error at '%s'", msg);
1005}
1006
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001007static void syntax_error_unterm_str(unsigned lineno, const char *s)
1008{
1009 die_if_script(lineno, "syntax error: unterminated %s", s);
1010}
1011
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001012/* It so happens that all such cases are totally fatal
1013 * even if shell is interactive: EOF while looking for closing
1014 * delimiter. There is nowhere to read stuff from after that,
1015 * it's EOF! The only choice is to terminate.
1016 */
1017static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001018static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001019{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001020 char msg[2] = { ch, '\0' };
1021 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001022 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001023}
1024
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001025static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001026{
1027 char msg[2];
1028 msg[0] = ch;
1029 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001030 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001031}
1032
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001033#if HUSH_DEBUG < 2
1034# undef die_if_script
1035# undef syntax_error
1036# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001037# undef syntax_error_unterm_ch
1038# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001039# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001040#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001041# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001042# define syntax_error(msg) syntax_error(__LINE__, msg)
1043# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1044# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1045# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1046# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001047#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001048
Denis Vlasenko552433b2009-04-04 19:29:21 +00001049
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001050#if ENABLE_HUSH_INTERACTIVE
1051static void cmdedit_update_prompt(void);
1052#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001053# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001054#endif
1055
1056
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001057/* Utility functions
1058 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001059/* Replace each \x with x in place, return ptr past NUL. */
1060static char *unbackslash(char *src)
1061{
Denys Vlasenko71885402009-09-24 01:44:13 +02001062 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001063 while (1) {
1064 if (*src == '\\')
1065 src++;
1066 if ((*dst++ = *src++) == '\0')
1067 break;
1068 }
1069 return dst;
1070}
1071
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001072static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001073{
1074 int i;
1075 unsigned count1;
1076 unsigned count2;
1077 char **v;
1078
1079 v = strings;
1080 count1 = 0;
1081 if (v) {
1082 while (*v) {
1083 count1++;
1084 v++;
1085 }
1086 }
1087 count2 = 0;
1088 v = add;
1089 while (*v) {
1090 count2++;
1091 v++;
1092 }
1093 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1094 v[count1 + count2] = NULL;
1095 i = count2;
1096 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001097 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001098 return v;
1099}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001100#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001101static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1102{
1103 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1104 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1105 return ptr;
1106}
1107#define add_strings_to_strings(strings, add, need_to_dup) \
1108 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1109#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001110
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001111/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001112static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001113{
1114 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001115 v[0] = add;
1116 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001117 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001118}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001119#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001120static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1121{
1122 char **ptr = add_string_to_strings(strings, add);
1123 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1124 return ptr;
1125}
1126#define add_string_to_strings(strings, add) \
1127 xx_add_string_to_strings(__LINE__, strings, add)
1128#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001129
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001130static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001131{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001132 char **v;
1133
1134 if (!strings)
1135 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001136 v = strings;
1137 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001138 free(*v);
1139 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001140 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001141 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001142}
1143
Denis Vlasenko76d50412008-06-10 16:19:39 +00001144
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001145/* Helpers for setting new $n and restoring them back
1146 */
1147typedef struct save_arg_t {
1148 char *sv_argv0;
1149 char **sv_g_argv;
1150 int sv_g_argc;
1151 smallint sv_g_malloced;
1152} save_arg_t;
1153
1154static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1155{
1156 int n;
1157
1158 sv->sv_argv0 = argv[0];
1159 sv->sv_g_argv = G.global_argv;
1160 sv->sv_g_argc = G.global_argc;
1161 sv->sv_g_malloced = G.global_args_malloced;
1162
1163 argv[0] = G.global_argv[0]; /* retain $0 */
1164 G.global_argv = argv;
1165 G.global_args_malloced = 0;
1166
1167 n = 1;
1168 while (*++argv)
1169 n++;
1170 G.global_argc = n;
1171}
1172
1173static void restore_G_args(save_arg_t *sv, char **argv)
1174{
1175 char **pp;
1176
1177 if (G.global_args_malloced) {
1178 /* someone ran "set -- arg1 arg2 ...", undo */
1179 pp = G.global_argv;
1180 while (*++pp) /* note: does not free $0 */
1181 free(*pp);
1182 free(G.global_argv);
1183 }
1184 argv[0] = sv->sv_argv0;
1185 G.global_argv = sv->sv_g_argv;
1186 G.global_argc = sv->sv_g_argc;
1187 G.global_args_malloced = sv->sv_g_malloced;
1188}
1189
1190
Denis Vlasenkod5762932009-03-31 11:22:57 +00001191/* Basic theory of signal handling in shell
1192 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001193 * This does not describe what hush does, rather, it is current understanding
1194 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001195 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1196 *
1197 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1198 * is finished or backgrounded. It is the same in interactive and
1199 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001200 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001201 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001202 * backgrounds (i.e. stops) or kills all members of currently running
1203 * pipe.
1204 *
1205 * Wait builtin in interruptible by signals for which user trap is set
1206 * or by SIGINT in interactive shell.
1207 *
1208 * Trap handlers will execute even within trap handlers. (right?)
1209 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001210 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1211 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001212 *
1213 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001214 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001215 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001216 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001217 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001218 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001219 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001220 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001221 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001222 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001223 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001224 *
1225 * SIGQUIT: ignore
1226 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001227 * SIGHUP (interactive):
1228 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001229 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001230 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1231 * that all pipe members are stopped. Try this in bash:
1232 * while :; do :; done - ^Z does not background it
1233 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001234 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001235 * of the command line, show prompt. NB: ^C does not send SIGINT
1236 * to interactive shell while shell is waiting for a pipe,
1237 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001238 * Example 1: this waits 5 sec, but does not execute ls:
1239 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1240 * Example 2: this does not wait and does not execute ls:
1241 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1242 * Example 3: this does not wait 5 sec, but executes ls:
1243 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001244 *
1245 * (What happens to signals which are IGN on shell start?)
1246 * (What happens with signal mask on shell start?)
1247 *
1248 * Implementation in hush
1249 * ======================
1250 * We use in-kernel pending signal mask to determine which signals were sent.
1251 * We block all signals which we don't want to take action immediately,
1252 * i.e. we block all signals which need to have special handling as described
1253 * above, and all signals which have traps set.
1254 * After each pipe execution, we extract any pending signals via sigtimedwait()
1255 * and act on them.
1256 *
1257 * unsigned non_DFL_mask: a mask of such "special" signals
1258 * sigset_t blocked_set: current blocked signal set
1259 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001260 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001261 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001262 * "trap 'cmd' SIGxxx":
1263 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001264 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001265 * unblock signals with special interactive handling
1266 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001267 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001268 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001269 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001270 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001271 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001272 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001273 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001274 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001275 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001276 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001277 * Standard says "When a subshell is entered, traps that are not being ignored
1278 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001279 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001280 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001281enum {
1282 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001283 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001284 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001285 | (1 << SIGHUP)
1286 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001287 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001288#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001289 | (1 << SIGTTIN)
1290 | (1 << SIGTTOU)
1291 | (1 << SIGTSTP)
1292#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001293};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001294
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001295#if ENABLE_HUSH_FAST
1296static void SIGCHLD_handler(int sig UNUSED_PARAM)
1297{
1298 G.count_SIGCHLD++;
1299//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1300}
1301#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001302
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001303#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001304
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001305/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001306# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001307/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001308# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001309
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001310/* Restores tty foreground process group, and exits.
1311 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001312 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001313 * or called directly with -EXITCODE.
1314 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001315static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001316static void sigexit(int sig)
1317{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001318 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001319 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001320
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001321 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001322 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001323 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1324 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001325
1326 /* Not a signal, just exit */
1327 if (sig <= 0)
1328 _exit(- sig);
1329
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001330 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001331}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001332#else
1333
Denys Vlasenko8391c482010-05-22 17:50:43 +02001334# define disable_restore_tty_pgrp_on_exit() ((void)0)
1335# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001336
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001337#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001338
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001339/* Restores tty foreground process group, and exits. */
1340static void hush_exit(int exitcode) NORETURN;
1341static void hush_exit(int exitcode)
1342{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001343 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1344 /* Prevent recursion:
1345 * trap "echo Hi; exit" EXIT; exit
1346 */
1347 char *argv[] = { NULL, G.traps[0], NULL };
1348 G.traps[0] = NULL;
1349 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001350 builtin_eval(argv);
1351 free(argv[1]);
1352 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001353
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001354#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001355 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001356 sigexit(- (exitcode & 0xff));
1357#else
1358 exit(exitcode);
1359#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001360}
1361
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001362static int check_and_run_traps(int sig)
1363{
Dan Fandrichfdd7b562010-06-18 22:37:42 -07001364 static const struct timespec zero_timespec;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001365 smalluint save_rcode;
1366 int last_sig = 0;
1367
1368 if (sig)
1369 goto jump_in;
1370 while (1) {
1371 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1372 if (sig <= 0)
1373 break;
1374 jump_in:
1375 last_sig = sig;
1376 if (G.traps && G.traps[sig]) {
1377 if (G.traps[sig][0]) {
1378 /* We have user-defined handler */
1379 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1380 save_rcode = G.last_exitcode;
1381 builtin_eval(argv);
1382 free(argv[1]);
1383 G.last_exitcode = save_rcode;
1384 } /* else: "" trap, ignoring signal */
1385 continue;
1386 }
1387 /* not a trap: special action */
1388 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001389#if ENABLE_HUSH_FAST
1390 case SIGCHLD:
1391 G.count_SIGCHLD++;
1392//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1393 break;
1394#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001395 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001396 /* Builtin was ^C'ed, make it look prettier: */
1397 bb_putchar('\n');
1398 G.flag_SIGINT = 1;
1399 break;
1400#if ENABLE_HUSH_JOB
1401 case SIGHUP: {
1402 struct pipe *job;
1403 /* bash is observed to signal whole process groups,
1404 * not individual processes */
1405 for (job = G.job_list; job; job = job->next) {
1406 if (job->pgrp <= 0)
1407 continue;
1408 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1409 if (kill(- job->pgrp, SIGHUP) == 0)
1410 kill(- job->pgrp, SIGCONT);
1411 }
1412 sigexit(SIGHUP);
1413 }
1414#endif
1415 default: /* ignored: */
1416 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1417 break;
1418 }
1419 }
1420 return last_sig;
1421}
1422
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001423
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001424static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001425{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001426 if (force || G.cwd == NULL) {
1427 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1428 * we must not try to free(bb_msg_unknown) */
1429 if (G.cwd == bb_msg_unknown)
1430 G.cwd = NULL;
1431 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1432 if (!G.cwd)
1433 G.cwd = bb_msg_unknown;
1434 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001435 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001436}
1437
Denis Vlasenko83506862007-11-23 13:11:42 +00001438
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001439/*
1440 * Shell and environment variable support
1441 */
1442static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001443{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001444 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001445 struct variable *cur;
1446 int len;
1447
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001448 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001449 pp = &G.top_var;
1450 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001451 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001452 return pp;
1453 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001454 }
1455 return NULL;
1456}
1457
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001458static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001459{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001460 struct variable **pp = get_ptr_to_local_var(name);
1461 if (pp)
1462 return *pp;
1463 return NULL;
1464}
1465
Denys Vlasenko03dad222010-01-12 23:29:57 +01001466static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001467{
Denys Vlasenko29082232010-07-16 13:52:32 +02001468 struct variable **vpp;
1469
1470 if (G.expanded_assignments) {
1471 char **cpp = G.expanded_assignments;
1472 int len = strlen(name);
1473 while (*cpp) {
1474 char *cp = *cpp;
1475 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1476 return cp + len + 1;
1477 cpp++;
1478 }
1479 }
1480
1481 vpp = get_ptr_to_local_var(name);
1482 if (vpp)
1483 return strchr((*vpp)->varstr, '=') + 1;
1484
Denys Vlasenkodea47882009-10-09 15:40:49 +02001485 if (strcmp(name, "PPID") == 0)
1486 return utoa(G.root_ppid);
1487 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001488#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001489 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001490 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001491 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001492#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001493 return NULL;
1494}
1495
1496/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001497 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001498 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001499 * 0: do not change export flag
1500 * (if creating new variable, flag will be 0)
1501 * 1: set export flag and putenv the variable
1502 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001503 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001504 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001505#if !BB_MMU && ENABLE_HUSH_LOCAL
1506/* all params are used */
1507#elif BB_MMU && ENABLE_HUSH_LOCAL
1508#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1509 set_local_var(str, flg_export, local_lvl)
1510#elif BB_MMU && !ENABLE_HUSH_LOCAL
1511#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001512 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001513#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1514#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1515 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001516#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001517static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001518{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001519 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001520 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001521 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001522 int name_len;
1523
Denis Vlasenko950bd722009-04-21 11:23:56 +00001524 eq_sign = strchr(str, '=');
1525 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001526 free(str);
1527 return -1;
1528 }
1529
Denis Vlasenko950bd722009-04-21 11:23:56 +00001530 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001531 var_pp = &G.top_var;
1532 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001533 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001534 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001535 continue;
1536 }
1537 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001538 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001539#if !BB_MMU
1540 if (!flg_read_only)
1541#endif
1542 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001543 free(str);
1544 return -1;
1545 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001546 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001547 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1548 *eq_sign = '\0';
1549 unsetenv(str);
1550 *eq_sign = '=';
1551 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001552#if ENABLE_HUSH_LOCAL
1553 if (cur->func_nest_level < local_lvl) {
1554 /* New variable is declared as local,
1555 * and existing one is global, or local
1556 * from enclosing function.
1557 * Remove and save old one: */
1558 *var_pp = cur->next;
1559 cur->next = *G.shadowed_vars_pp;
1560 *G.shadowed_vars_pp = cur;
1561 /* bash 3.2.33(1) and exported vars:
1562 * # export z=z
1563 * # f() { local z=a; env | grep ^z; }
1564 * # f
1565 * z=a
1566 * # env | grep ^z
1567 * z=z
1568 */
1569 if (cur->flg_export)
1570 flg_export = 1;
1571 break;
1572 }
1573#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001574 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001575 free_and_exp:
1576 free(str);
1577 goto exp;
1578 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001579 if (cur->max_len != 0) {
1580 if (cur->max_len >= strlen(str)) {
1581 /* This one is from startup env, reuse space */
1582 strcpy(cur->varstr, str);
1583 goto free_and_exp;
1584 }
1585 } else {
1586 /* max_len == 0 signifies "malloced" var, which we can
1587 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001588 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001589 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001590 cur->max_len = 0;
1591 goto set_str_and_exp;
1592 }
1593
Denys Vlasenko295fef82009-06-03 12:47:26 +02001594 /* Not found - create new variable struct */
1595 cur = xzalloc(sizeof(*cur));
1596#if ENABLE_HUSH_LOCAL
1597 cur->func_nest_level = local_lvl;
1598#endif
1599 cur->next = *var_pp;
1600 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001601
1602 set_str_and_exp:
1603 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001604#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001605 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001606#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001607 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001608 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001609 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001610 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1611 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001612 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001613 if (flg_export == -1) {
1614 cur->flg_export = 0;
1615 /* unsetenv was already done */
1616 } else {
1617 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1618 return putenv(cur->varstr);
1619 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001620 }
1621 return 0;
1622}
1623
Denys Vlasenko6db47842009-09-05 20:15:17 +02001624/* Used at startup and after each cd */
1625static void set_pwd_var(int exp)
1626{
1627 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1628 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1629}
1630
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001631static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001632{
1633 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001634 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001635
1636 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001637 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001638 var_pp = &G.top_var;
1639 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001640 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1641 if (cur->flg_read_only) {
1642 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001643 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001644 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001645 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001646 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1647 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001648 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1649 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001650 if (!cur->max_len)
1651 free(cur->varstr);
1652 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001653 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001654 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001655 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001656 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001657 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001658}
1659
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001660static int unset_local_var(const char *name)
1661{
1662 return unset_local_var_len(name, strlen(name));
1663}
1664
1665static void unset_vars(char **strings)
1666{
1667 char **v;
1668
1669 if (!strings)
1670 return;
1671 v = strings;
1672 while (*v) {
1673 const char *eq = strchrnul(*v, '=');
1674 unset_local_var_len(*v, (int)(eq - *v));
1675 v++;
1676 }
1677 free(strings);
1678}
1679
Mike Frysinger98c52642009-04-02 10:02:37 +00001680#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko8391c482010-05-22 17:50:43 +02001681# define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1682# define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denys Vlasenko03dad222010-01-12 23:29:57 +01001683static char* FAST_FUNC endofname(const char *name)
Mike Frysinger98c52642009-04-02 10:02:37 +00001684{
1685 char *p;
1686
1687 p = (char *) name;
1688 if (!is_name(*p))
1689 return p;
1690 while (*++p) {
1691 if (!is_in_name(*p))
1692 break;
1693 }
1694 return p;
1695}
Denys Vlasenko6b01b712010-01-24 22:52:21 +01001696#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001697
Denys Vlasenko03dad222010-01-12 23:29:57 +01001698static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001699{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001700 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001701 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001702}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001703
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001704
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001705/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001706 * Helpers for "var1=val1 var2=val2 cmd" feature
1707 */
1708static void add_vars(struct variable *var)
1709{
1710 struct variable *next;
1711
1712 while (var) {
1713 next = var->next;
1714 var->next = G.top_var;
1715 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001716 if (var->flg_export) {
1717 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001718 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001719 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001720 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001721 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001722 var = next;
1723 }
1724}
1725
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001726static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001727{
1728 char **s;
1729 struct variable *old = NULL;
1730
1731 if (!strings)
1732 return old;
1733 s = strings;
1734 while (*s) {
1735 struct variable *var_p;
1736 struct variable **var_pp;
1737 char *eq;
1738
1739 eq = strchr(*s, '=');
1740 if (eq) {
1741 *eq = '\0';
1742 var_pp = get_ptr_to_local_var(*s);
1743 *eq = '=';
1744 if (var_pp) {
1745 /* Remove variable from global linked list */
1746 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001747 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001748 *var_pp = var_p->next;
1749 /* Add it to returned list */
1750 var_p->next = old;
1751 old = var_p;
1752 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001753 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001754 }
1755 s++;
1756 }
1757 return old;
1758}
1759
1760
1761/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001762 * in_str support
1763 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001764static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001765{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001766 int ch = *i->p;
1767 if (ch != '\0') {
1768 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001769 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001770 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001771 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001772}
1773
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001774static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001775{
1776 return *i->p;
1777}
1778
1779#if ENABLE_HUSH_INTERACTIVE
1780
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001781static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001782{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001783 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001784 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001785 if (G.PS1 == NULL)
1786 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001787 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001788 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001789 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001790 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001791 if (G.PS2 == NULL)
1792 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001793}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001794
1795static const char* setup_prompt_string(int promptmode)
1796{
1797 const char *prompt_str;
1798 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001799 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1800 /* Set up the prompt */
1801 if (promptmode == 0) { /* PS1 */
1802 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001803 /* bash uses $PWD value, even if it is set by user.
1804 * It uses current dir only if PWD is unset.
1805 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001806 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001807 prompt_str = G.PS1;
1808 } else
1809 prompt_str = G.PS2;
1810 } else
1811 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001812 debug_printf("result '%s'\n", prompt_str);
1813 return prompt_str;
1814}
1815
1816static void get_user_input(struct in_str *i)
1817{
1818 int r;
1819 const char *prompt_str;
1820
1821 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001822# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001823 /* Enable command line editing only while a command line
1824 * is actually being read */
1825 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001826 G.flag_SIGINT = 0;
1827 /* buglet: SIGINT will not make new prompt to appear _at once_,
1828 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001829 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 +00001830 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001831 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001832 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001833 i->eof_flag = (r < 0);
1834 if (i->eof_flag) { /* EOF/error detected */
1835 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1836 G.user_input_buf[1] = '\0';
1837 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001838# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001839 do {
1840 G.flag_SIGINT = 0;
1841 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001842 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001843 G.user_input_buf[0] = r = fgetc(i->file);
1844 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001845//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001846 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001847 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001848# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001849 i->p = G.user_input_buf;
1850}
1851
1852#endif /* INTERACTIVE */
1853
1854/* This is the magic location that prints prompts
1855 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001856static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001857{
1858 int ch;
1859
1860 /* If there is data waiting, eat it up */
1861 if (i->p && *i->p) {
1862#if ENABLE_HUSH_INTERACTIVE
1863 take_cached:
1864#endif
1865 ch = *i->p++;
1866 if (i->eof_flag && !*i->p)
1867 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001868 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001869 } else {
1870 /* need to double check i->file because we might be doing something
1871 * more complicated by now, like sourcing or substituting. */
1872#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001873 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001874 do {
1875 get_user_input(i);
1876 } while (!*i->p); /* need non-empty line */
1877 i->promptmode = 1; /* PS2 */
1878 i->promptme = 0;
1879 goto take_cached;
1880 }
1881#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001882 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001883 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001884 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001885#if ENABLE_HUSH_INTERACTIVE
1886 if (ch == '\n')
1887 i->promptme = 1;
1888#endif
1889 return ch;
1890}
1891
Denis Vlasenko913a2012009-04-05 22:17:04 +00001892/* All callers guarantee this routine will never
1893 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001894 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001895static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001896{
1897 int ch;
1898 if (i->p && *i->p) {
1899 if (i->eof_flag && !i->p[1])
1900 return EOF;
1901 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001902 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001903 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001904 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001905 i->eof_flag = (ch == EOF);
1906 i->peek_buf[0] = ch;
1907 i->peek_buf[1] = '\0';
1908 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001909 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001910 return ch;
1911}
1912
1913static void setup_file_in_str(struct in_str *i, FILE *f)
1914{
1915 i->peek = file_peek;
1916 i->get = file_get;
1917#if ENABLE_HUSH_INTERACTIVE
1918 i->promptme = 1;
1919 i->promptmode = 0; /* PS1 */
1920#endif
1921 i->file = f;
1922 i->p = NULL;
1923}
1924
1925static void setup_string_in_str(struct in_str *i, const char *s)
1926{
1927 i->peek = static_peek;
1928 i->get = static_get;
1929#if ENABLE_HUSH_INTERACTIVE
1930 i->promptme = 1;
1931 i->promptmode = 0; /* PS1 */
1932#endif
1933 i->p = s;
1934 i->eof_flag = 0;
1935}
1936
1937
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001938/*
1939 * o_string support
1940 */
1941#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001942
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001943static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001944{
1945 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02001946 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001947 if (o->data)
1948 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001949}
1950
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001951static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001952{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001953 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001954 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001955}
1956
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001957static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1958{
1959 free(o->data);
1960}
1961
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001962static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001963{
1964 if (o->length + len > o->maxlen) {
1965 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1966 o->data = xrealloc(o->data, 1 + o->maxlen);
1967 }
1968}
1969
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001970static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001971{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001972 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1973 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001974 o->data[o->length] = ch;
1975 o->length++;
1976 o->data[o->length] = '\0';
1977}
1978
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001979static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001980{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001981 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001982 memcpy(&o->data[o->length], str, len);
1983 o->length += len;
1984 o->data[o->length] = '\0';
1985}
1986
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001987static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001988{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001989 o_addblock(o, str, strlen(str));
1990}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02001991
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001992#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001993static void nommu_addchr(o_string *o, int ch)
1994{
1995 if (o)
1996 o_addchr(o, ch);
1997}
1998#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001999# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002000#endif
2001
2002static void o_addstr_with_NUL(o_string *o, const char *str)
2003{
2004 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002005}
2006
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002007static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00002008{
2009 while (len) {
2010 o_addchr(o, *str);
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002011 if (*str == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002012 o_addchr(o, '\\');
2013 }
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002014 str++;
Denis Vlasenko55789c62008-06-18 16:30:42 +00002015 len--;
2016 }
2017}
2018
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002019#undef HUSH_BRACE_EXP
2020/*
2021 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2022 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2023 * Apparently, on unquoted $v bash still does globbing
2024 * ("v='*.txt'; echo $v" prints all .txt files),
2025 * but NOT brace expansion! Thus, there should be TWO independent
2026 * quoting mechanisms on $v expansion side: one protects
2027 * $v from brace expansion, and other additionally protects "$v" against globbing.
2028 * We have only second one.
2029 */
2030
2031#ifdef HUSH_BRACE_EXP
2032# define MAYBE_BRACES "{}"
2033#else
2034# define MAYBE_BRACES ""
2035#endif
2036
Eric Andersen25f27032001-04-26 23:22:31 +00002037/* My analysis of quoting semantics tells me that state information
2038 * is associated with a destination, not a source.
2039 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002040static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002041{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002042 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002043 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002044 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002045 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002046 o_grow_by(o, sz);
2047 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002048 o->data[o->length] = '\\';
2049 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002050 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002051 o->data[o->length] = ch;
2052 o->length++;
2053 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002054}
2055
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002056static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002057{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002058 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002059 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002060 sz++;
2061 o->data[o->length] = '\\';
2062 o->length++;
2063 }
2064 o_grow_by(o, sz);
2065 o->data[o->length] = ch;
2066 o->length++;
2067 o->data[o->length] = '\0';
2068}
2069
Denys Vlasenko38292b62010-09-05 14:49:40 +02002070static void o_addQblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002071{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002072 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002073 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002074 return;
2075 }
2076 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002077 char ch;
2078 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002079 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002080 if (ordinary_cnt > len) /* paranoia */
2081 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002082 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002083 if (ordinary_cnt == len)
2084 return;
2085 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002086 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002087
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002088 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002089 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002090 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002091 sz++;
2092 o->data[o->length] = '\\';
2093 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002094 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002095 o_grow_by(o, sz);
2096 o->data[o->length] = ch;
2097 o->length++;
2098 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002099 }
2100}
2101
Denys Vlasenko38292b62010-09-05 14:49:40 +02002102static void o_addQstr(o_string *o, const char *str)
2103{
2104 o_addQblock(o, str, strlen(str));
2105}
2106
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002107/* A special kind of o_string for $VAR and `cmd` expansion.
2108 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002109 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002110 * list[i] contains an INDEX (int!) into this string data.
2111 * It means that if list[] needs to grow, data needs to be moved higher up
2112 * but list[i]'s need not be modified.
2113 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002114 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002115 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2116 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002117#if DEBUG_EXPAND || DEBUG_GLOB
2118static void debug_print_list(const char *prefix, o_string *o, int n)
2119{
2120 char **list = (char**)o->data;
2121 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2122 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002123
2124 indent();
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002125 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
Denys Vlasenko38292b62010-09-05 14:49:40 +02002126 prefix, list, n, string_start, o->length, o->maxlen, o->o_glob, o->has_quoted_part, o->o_escape);
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 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002176 list[n] = (char*)(ptrdiff_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
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002186 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002187}
2188
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002189#ifdef HUSH_BRACE_EXP
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 Vlasenko5b2db972009-11-16 05:49:36 +01002224 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2225 break;
2226 if (*cp++ == '{') /*}*/
2227 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 Vlasenko5b2db972009-11-16 05:49:36 +01002248 if (*begin == '{') /*}*/ {
2249 /* 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 }
2256 /*{*/ if (*next == '}') {
2257 /* "{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;
2273 /*{*/ while (*rest != '}') {
2274 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 Vlasenko5b2db972009-11-16 05:49:36 +01002309 /*{*/ if (*next == '}') {
2310 /* 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 */
2359static int o_glob(o_string *o, int n)
2360{
2361 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002362
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002363 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2364 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)
2381 debug_print_list("o_glob returning", o, n);
2382 return n;
2383}
2384
Denys Vlasenko8391c482010-05-22 17:50:43 +02002385#else /* !HUSH_BRACE_EXP */
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 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002406static int o_glob(o_string *o, int n)
2407{
2408 glob_t globdata;
2409 int gr;
2410 char *pattern;
2411
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002412 debug_printf_glob("start o_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)
2458 debug_print_list("o_glob returning", o, n);
2459 return n;
2460}
2461
Denys Vlasenko8391c482010-05-22 17:50:43 +02002462#endif /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002463
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002464/* If o->o_glob == 1, glob the string so far remembered.
2465 * 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{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002468 if (o->o_glob) { /* if globbing is requested */
2469 /* 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)
2473 return o_glob(o, n); /* o_save_ptr_helper is inside */
2474 }
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--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002493 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002494 }
2495 return list;
2496}
2497
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002498static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002499
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002500/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002501static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002502{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002503 char **p;
2504 struct command *command;
2505 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002506 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002507
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002508 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002509 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002510 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002511 for (i = 0; i < pi->num_cmds; i++) {
2512 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002513 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002514 if (command->argv) {
2515 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002516 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002517 }
2518 free_strings(command->argv);
2519 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002520 }
2521 /* not "else if": on syntax error, we may have both! */
2522 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002523 debug_printf_clean(" begin group (cmd_type:%d)\n",
2524 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002525 free_pipe_list(command->group);
2526 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002527 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002528 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002529 /* else is crucial here.
2530 * If group != NULL, child_func is meaningless */
2531#if ENABLE_HUSH_FUNCTIONS
2532 else if (command->child_func) {
2533 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2534 command->child_func->parent_cmd = NULL;
2535 }
2536#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002537#if !BB_MMU
2538 free(command->group_as_string);
2539 command->group_as_string = NULL;
2540#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002541 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002542 debug_printf_clean(" redirect %d%s",
2543 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002544 /* guard against the case >$FOO, where foo is unset or blank */
2545 if (r->rd_filename) {
2546 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2547 free(r->rd_filename);
2548 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002549 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002550 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002551 rnext = r->next;
2552 free(r);
2553 }
2554 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002555 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556 free(pi->cmds); /* children are an array, they get freed all at once */
2557 pi->cmds = NULL;
2558#if ENABLE_HUSH_JOB
2559 free(pi->cmdtext);
2560 pi->cmdtext = NULL;
2561#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002562}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002563
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002564static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002565{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002566 struct pipe *pi, *next;
2567
2568 for (pi = head; pi; pi = next) {
2569#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002570 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002571#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002572 free_pipe(pi);
2573 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002574 next = pi->next;
2575 /*pi->next = NULL;*/
2576 free(pi);
2577 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002578}
2579
2580
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002581/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002582
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002583static struct pipe *new_pipe(void)
2584{
Eric Andersen25f27032001-04-26 23:22:31 +00002585 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002586 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002587 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002588 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002589 return pi;
2590}
2591
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002592/* Command (member of a pipe) is complete, or we start a new pipe
2593 * if ctx->command is NULL.
2594 * No errors possible here.
2595 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002596static int done_command(struct parse_context *ctx)
2597{
2598 /* The command is really already in the pipe structure, so
2599 * advance the pipe counter and make a new, null command. */
2600 struct pipe *pi = ctx->pipe;
2601 struct command *command = ctx->command;
2602
2603 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002604 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002605 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002606 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002607 }
2608 pi->num_cmds++;
2609 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002610 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002611 } else {
2612 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2613 }
2614
2615 /* Only real trickiness here is that the uncommitted
2616 * command structure is not counted in pi->num_cmds. */
2617 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002618 ctx->command = command = &pi->cmds[pi->num_cmds];
2619 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002620 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002621 return pi->num_cmds; /* used only for 0/nonzero check */
2622}
2623
2624static void done_pipe(struct parse_context *ctx, pipe_style type)
2625{
2626 int not_null;
2627
2628 debug_printf_parse("done_pipe entered, followup %d\n", type);
2629 /* Close previous command */
2630 not_null = done_command(ctx);
2631 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002632#if HAS_KEYWORDS
2633 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2634 ctx->ctx_inverted = 0;
2635 ctx->pipe->res_word = ctx->ctx_res_w;
2636#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002637
2638 /* Without this check, even just <enter> on command line generates
2639 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002640 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002641 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002642#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002643 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002644#endif
2645#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002646 || ctx->ctx_res_w == RES_DONE
2647 || ctx->ctx_res_w == RES_FOR
2648 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002649#endif
2650#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002651 || ctx->ctx_res_w == RES_ESAC
2652#endif
2653 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002654 struct pipe *new_p;
2655 debug_printf_parse("done_pipe: adding new pipe: "
2656 "not_null:%d ctx->ctx_res_w:%d\n",
2657 not_null, ctx->ctx_res_w);
2658 new_p = new_pipe();
2659 ctx->pipe->next = new_p;
2660 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002661 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002662 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002663 * This is used to control execution.
2664 * RES_FOR and RES_IN are NOT sticky (needed to support
2665 * cases where variable or value happens to match a keyword):
2666 */
2667#if ENABLE_HUSH_LOOPS
2668 if (ctx->ctx_res_w == RES_FOR
2669 || ctx->ctx_res_w == RES_IN)
2670 ctx->ctx_res_w = RES_NONE;
2671#endif
2672#if ENABLE_HUSH_CASE
2673 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002674 ctx->ctx_res_w = RES_CASE_BODY;
2675 if (ctx->ctx_res_w == RES_CASE)
2676 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002677#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002678 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002679 /* Create the memory for command, roughly:
2680 * ctx->pipe->cmds = new struct command;
2681 * ctx->command = &ctx->pipe->cmds[0];
2682 */
2683 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002684 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002685 }
2686 debug_printf_parse("done_pipe return\n");
2687}
2688
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002689static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002690{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002691 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002692 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002693 /* Create the memory for command, roughly:
2694 * ctx->pipe->cmds = new struct command;
2695 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002696 */
2697 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002698}
2699
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002700/* If a reserved word is found and processed, parse context is modified
2701 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002702 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002703#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002704struct reserved_combo {
2705 char literal[6];
2706 unsigned char res;
2707 unsigned char assignment_flag;
2708 int flag;
2709};
2710enum {
2711 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002712# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002713 FLAG_IF = (1 << RES_IF ),
2714 FLAG_THEN = (1 << RES_THEN ),
2715 FLAG_ELIF = (1 << RES_ELIF ),
2716 FLAG_ELSE = (1 << RES_ELSE ),
2717 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002718# endif
2719# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002720 FLAG_FOR = (1 << RES_FOR ),
2721 FLAG_WHILE = (1 << RES_WHILE),
2722 FLAG_UNTIL = (1 << RES_UNTIL),
2723 FLAG_DO = (1 << RES_DO ),
2724 FLAG_DONE = (1 << RES_DONE ),
2725 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002726# endif
2727# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002728 FLAG_MATCH = (1 << RES_MATCH),
2729 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002730# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002731 FLAG_START = (1 << RES_XXXX ),
2732};
2733
2734static const struct reserved_combo* match_reserved_word(o_string *word)
2735{
Eric Andersen25f27032001-04-26 23:22:31 +00002736 /* Mostly a list of accepted follow-up reserved words.
2737 * FLAG_END means we are done with the sequence, and are ready
2738 * to turn the compound list into a command.
2739 * FLAG_START means the word must start a new compound list.
2740 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002741 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002742# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002743 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2744 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2745 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2746 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2747 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2748 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002749# endif
2750# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002751 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2752 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2753 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2754 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2755 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2756 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002757# endif
2758# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002759 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2760 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002761# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002762 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002763 const struct reserved_combo *r;
2764
2765 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2766 if (strcmp(word->data, r->literal) == 0)
2767 return r;
2768 }
2769 return NULL;
2770}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002771/* Return 0: not a keyword, 1: keyword
2772 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002773static int reserved_word(o_string *word, struct parse_context *ctx)
2774{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002775# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002776 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002777 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002778 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002779# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002780 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002781
Denys Vlasenko38292b62010-09-05 14:49:40 +02002782 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002783 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002784 r = match_reserved_word(word);
2785 if (!r)
2786 return 0;
2787
2788 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002789# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002790 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2791 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002792 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002793 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002794# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002795 if (r->flag == 0) { /* '!' */
2796 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002797 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002798 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002799 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002800 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002801 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002802 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002803 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002804 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002805
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002806 old = xmalloc(sizeof(*old));
2807 debug_printf_parse("push stack %p\n", old);
2808 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002809 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002810 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002811 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002812 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002813 ctx->ctx_res_w = RES_SNTX;
2814 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002815 } else {
2816 /* "{...} fi" is ok. "{...} if" is not
2817 * Example:
2818 * if { echo foo; } then { echo bar; } fi */
2819 if (ctx->command->group)
2820 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002821 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002822
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002823 ctx->ctx_res_w = r->res;
2824 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002825 word->o_assignment = r->assignment_flag;
2826
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002827 if (ctx->old_flag & FLAG_END) {
2828 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002829
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002830 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002831 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002832 old = ctx->stack;
2833 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002834 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002835# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002836 o_addstr(&old->as_string, ctx->as_string.data);
2837 o_free_unsafe(&ctx->as_string);
2838 old->command->group_as_string = xstrdup(old->as_string.data);
2839 debug_printf_parse("pop, remembering as:'%s'\n",
2840 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002841# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002842 *ctx = *old; /* physical copy */
2843 free(old);
2844 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002845 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002846}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002847#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00002848
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002849/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002850 * Normal return is 0. Syntax errors return 1.
2851 * Note: on return, word is reset, but not o_free'd!
2852 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002853static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002854{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002855 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00002856
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002857 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02002858 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002859 debug_printf_parse("done_word return 0: true null, ignored\n");
2860 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002861 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002862
Eric Andersen25f27032001-04-26 23:22:31 +00002863 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002864 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2865 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002866 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2867 * "2.7 Redirection
2868 * ...the word that follows the redirection operator
2869 * shall be subjected to tilde expansion, parameter expansion,
2870 * command substitution, arithmetic expansion, and quote
2871 * removal. Pathname expansion shall not be performed
2872 * on the word by a non-interactive shell; an interactive
2873 * shell may perform it, but shall do so only when
2874 * the expansion would result in one word."
2875 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002876 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002877 /* Cater for >\file case:
2878 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2879 * Same with heredocs:
2880 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2881 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002882 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2883 unbackslash(ctx->pending_redirect->rd_filename);
2884 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02002885 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002886 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2887 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002888 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002889 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002890 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002891 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002892 /* If this word wasn't an assignment, next ones definitely
2893 * can't be assignments. Even if they look like ones. */
2894 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2895 && word->o_assignment != WORD_IS_KEYWORD
2896 ) {
2897 word->o_assignment = NOT_ASSIGNMENT;
2898 } else {
2899 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2900 command->assignment_cnt++;
2901 word->o_assignment = MAYBE_ASSIGNMENT;
2902 }
2903
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002904#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002905# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00002906 if (ctx->ctx_dsemicolon
2907 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2908 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00002909 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002910 /* ctx->ctx_res_w = RES_MATCH; */
2911 ctx->ctx_dsemicolon = 0;
2912 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002913# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002914 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002915# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002916 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2917 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002918# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002919# if ENABLE_HUSH_CASE
2920 && ctx->ctx_res_w != RES_CASE
2921# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002922 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002923 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002924 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002925 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002926 debug_printf_parse("done_word return %d\n",
2927 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002928 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002929 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002930# ifdef CMD_SINGLEWORD_NOGLOB_COND
2931 if (strcmp(word->data, "export") == 0
2932# if ENABLE_HUSH_LOCAL
2933 || strcmp(word->data, "local") == 0
2934# endif
2935 ) {
2936 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
2937 } else
2938# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002939# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002940 if (strcmp(word->data, "[[") == 0) {
2941 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2942 }
2943 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002944# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002945 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002946#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00002947 if (command->group) {
2948 /* "{ echo foo; } echo bar" - bad */
2949 syntax_error_at(word->data);
2950 debug_printf_parse("done_word return 1: syntax error, "
2951 "groups and arglists don't mix\n");
2952 return 1;
2953 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02002954 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00002955 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2956 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002957 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002958 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002959 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002960 char *p = word->data;
2961 while (p[0] == SPECIAL_VAR_SYMBOL
2962 && (p[1] & 0x7f) == '@'
2963 && p[2] == SPECIAL_VAR_SYMBOL
2964 ) {
2965 p += 3;
2966 }
2967 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002968 /* saw no "$@", or not only "$@" but some
2969 * real text is there too */
2970 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002971 * e.g. "", $empty"" etc to not disappear */
2972 o_addchr(word, SPECIAL_VAR_SYMBOL);
2973 o_addchr(word, SPECIAL_VAR_SYMBOL);
2974 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002975 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002976 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002977 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002978 }
Eric Andersen25f27032001-04-26 23:22:31 +00002979
Denis Vlasenko06810332007-05-21 23:30:54 +00002980#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002981 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02002982 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002983 || !is_well_formed_var_name(command->argv[0], '\0')
2984 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002985 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002986 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002987 return 1;
2988 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002989 /* Force FOR to have just one word (variable name) */
2990 /* NB: basically, this makes hush see "for v in ..."
2991 * syntax as if it is "for v; in ...". FOR and IN become
2992 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002993 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002994 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002995#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002996#if ENABLE_HUSH_CASE
2997 /* Force CASE to have just one word */
2998 if (ctx->ctx_res_w == RES_CASE) {
2999 done_pipe(ctx, PIPE_SEQ);
3000 }
3001#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003002
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003003 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003004
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003005 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003006 return 0;
3007}
3008
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003009
3010/* Peek ahead in the input to find out if we have a "&n" construct,
3011 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003012 * Return:
3013 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3014 * REDIRFD_SYNTAX_ERR if syntax error,
3015 * REDIRFD_TO_FILE if no & was seen,
3016 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003017 */
3018#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003019#define parse_redir_right_fd(as_string, input) \
3020 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003021#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003022static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003023{
3024 int ch, d, ok;
3025
3026 ch = i_peek(input);
3027 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003028 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003029
3030 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003031 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003032 ch = i_peek(input);
3033 if (ch == '-') {
3034 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003035 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003036 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003037 }
3038 d = 0;
3039 ok = 0;
3040 while (ch != EOF && isdigit(ch)) {
3041 d = d*10 + (ch-'0');
3042 ok = 1;
3043 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003044 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003045 ch = i_peek(input);
3046 }
3047 if (ok) return d;
3048
3049//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3050
3051 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003052 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003053}
3054
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003055/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003056 */
3057static int parse_redirect(struct parse_context *ctx,
3058 int fd,
3059 redir_type style,
3060 struct in_str *input)
3061{
3062 struct command *command = ctx->command;
3063 struct redir_struct *redir;
3064 struct redir_struct **redirp;
3065 int dup_num;
3066
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003067 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003068 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003069 /* Check for a '>&1' type redirect */
3070 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3071 if (dup_num == REDIRFD_SYNTAX_ERR)
3072 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003073 } else {
3074 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003075 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003076 if (dup_num) { /* <<-... */
3077 ch = i_getch(input);
3078 nommu_addchr(&ctx->as_string, ch);
3079 ch = i_peek(input);
3080 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003081 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003082
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003083 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003084 int ch = i_peek(input);
3085 if (ch == '|') {
3086 /* >|FILE redirect ("clobbering" >).
3087 * Since we do not support "set -o noclobber" yet,
3088 * >| and > are the same for now. Just eat |.
3089 */
3090 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003091 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003092 }
3093 }
3094
3095 /* Create a new redir_struct and append it to the linked list */
3096 redirp = &command->redirects;
3097 while ((redir = *redirp) != NULL) {
3098 redirp = &(redir->next);
3099 }
3100 *redirp = redir = xzalloc(sizeof(*redir));
3101 /* redir->next = NULL; */
3102 /* redir->rd_filename = NULL; */
3103 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003104 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003105
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003106 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3107 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003108
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003109 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003110 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003111 /* Erik had a check here that the file descriptor in question
3112 * is legit; I postpone that to "run time"
3113 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003114 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3115 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003116 } else {
3117 /* Set ctx->pending_redirect, so we know what to do at the
3118 * end of the next parsed word. */
3119 ctx->pending_redirect = redir;
3120 }
3121 return 0;
3122}
3123
Eric Andersen25f27032001-04-26 23:22:31 +00003124/* If a redirect is immediately preceded by a number, that number is
3125 * supposed to tell which file descriptor to redirect. This routine
3126 * looks for such preceding numbers. In an ideal world this routine
3127 * needs to handle all the following classes of redirects...
3128 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3129 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3130 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3131 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003132 *
3133 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3134 * "2.7 Redirection
3135 * ... If n is quoted, the number shall not be recognized as part of
3136 * the redirection expression. For example:
3137 * echo \2>a
3138 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003139 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003140 *
3141 * A -1 return means no valid number was found,
3142 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003143 */
3144static int redirect_opt_num(o_string *o)
3145{
3146 int num;
3147
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003148 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003149 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003150 num = bb_strtou(o->data, NULL, 10);
3151 if (errno || num < 0)
3152 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003153 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003154 return num;
3155}
3156
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003157#if BB_MMU
3158#define fetch_till_str(as_string, input, word, skip_tabs) \
3159 fetch_till_str(input, word, skip_tabs)
3160#endif
3161static char *fetch_till_str(o_string *as_string,
3162 struct in_str *input,
3163 const char *word,
3164 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003165{
3166 o_string heredoc = NULL_O_STRING;
3167 int past_EOL = 0;
3168 int ch;
3169
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003170 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003171 while (1) {
3172 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003173 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003174 if (ch == '\n') {
3175 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3176 heredoc.data[past_EOL] = '\0';
3177 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3178 return heredoc.data;
3179 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003180 do {
3181 o_addchr(&heredoc, ch);
3182 past_EOL = heredoc.length;
3183 jump_in:
3184 do {
3185 ch = i_getch(input);
3186 nommu_addchr(as_string, ch);
3187 } while (skip_tabs && ch == '\t');
3188 } while (ch == '\n');
3189 }
3190 if (ch == EOF) {
3191 o_free_unsafe(&heredoc);
3192 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003193 }
3194 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003195 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003196 }
3197}
3198
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003199/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3200 * and load them all. There should be exactly heredoc_cnt of them.
3201 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003202static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3203{
3204 struct pipe *pi = ctx->list_head;
3205
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003206 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003207 int i;
3208 struct command *cmd = pi->cmds;
3209
3210 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3211 pi->num_cmds,
3212 cmd->argv ? cmd->argv[0] : "NONE");
3213 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003214 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003215
3216 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3217 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003218 while (redir) {
3219 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003220 char *p;
3221
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003222 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003223 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003224 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003225 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003226 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003227 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003228 return 1;
3229 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003230 free(redir->rd_filename);
3231 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003232 heredoc_cnt--;
3233 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003234 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003235 }
3236 cmd++;
3237 }
3238 pi = pi->next;
3239 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003240#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003241 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003242 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003243 bb_error_msg_and_die("heredoc BUG 2");
3244#endif
3245 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003246}
3247
3248
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003249static int run_list(struct pipe *pi);
3250#if BB_MMU
3251#define parse_stream(pstring, input, end_trigger) \
3252 parse_stream(input, end_trigger)
3253#endif
3254static struct pipe *parse_stream(char **pstring,
3255 struct in_str *input,
3256 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003257
Eric Andersen25f27032001-04-26 23:22:31 +00003258
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003259#if !ENABLE_HUSH_FUNCTIONS
3260#define parse_group(dest, ctx, input, ch) \
3261 parse_group(ctx, input, ch)
3262#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003263static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003264 struct in_str *input, int ch)
3265{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003266 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003267 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003268 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003269 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003270 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003271 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003272
3273 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003274#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003275 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003276 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003277 if (done_word(dest, ctx))
3278 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003279 if (!command->argv)
3280 goto skip; /* (... */
3281 if (command->argv[1]) { /* word word ... (... */
3282 syntax_error_unexpected_ch('(');
3283 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003284 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003285 /* it is "word(..." or "word (..." */
3286 do
3287 ch = i_getch(input);
3288 while (ch == ' ' || ch == '\t');
3289 if (ch != ')') {
3290 syntax_error_unexpected_ch(ch);
3291 return 1;
3292 }
3293 nommu_addchr(&ctx->as_string, ch);
3294 do
3295 ch = i_getch(input);
3296 while (ch == ' ' || ch == '\t' || ch == '\n');
3297 if (ch != '{') {
3298 syntax_error_unexpected_ch(ch);
3299 return 1;
3300 }
3301 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003302 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003303 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003304 }
3305#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003306
3307#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003308 if (command->argv /* word [word]{... */
3309 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003310 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003311 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003312 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003313 debug_printf_parse("parse_group return 1: "
3314 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003315 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003316 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003317#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003318
3319#if ENABLE_HUSH_FUNCTIONS
3320 skip:
3321#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003322 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003323 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003324 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003325 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003326 } else {
3327 /* bash does not allow "{echo...", requires whitespace */
3328 ch = i_getch(input);
3329 if (ch != ' ' && ch != '\t' && ch != '\n') {
3330 syntax_error_unexpected_ch(ch);
3331 return 1;
3332 }
3333 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003334 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003335
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003336 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003337#if BB_MMU
3338# define as_string NULL
3339#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003340 char *as_string = NULL;
3341#endif
3342 pipe_list = parse_stream(&as_string, input, endch);
3343#if !BB_MMU
3344 if (as_string)
3345 o_addstr(&ctx->as_string, as_string);
3346#endif
3347 /* empty ()/{} or parse error? */
3348 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003349 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003350 if (!BB_MMU)
3351 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003352 debug_printf_parse("parse_group return 1: "
3353 "parse_stream returned %p\n", pipe_list);
3354 return 1;
3355 }
3356 command->group = pipe_list;
3357#if !BB_MMU
3358 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3359 command->group_as_string = as_string;
3360 debug_printf_parse("end of group, remembering as:'%s'\n",
3361 command->group_as_string);
3362#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003363#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003364 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003365 debug_printf_parse("parse_group return 0\n");
3366 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003367 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003368}
3369
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003370#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003371/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003372static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003373/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003374static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003375{
3376 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003377 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003378 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003379 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003380 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003381 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003382 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003383 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003384 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003385 }
3386}
3387/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003388static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003389{
3390 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003391 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003392 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003393 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003394 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003395 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003396 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003397 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003398 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003399 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003400 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003401 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003402 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003403 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003404 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003405 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003406 continue;
3407 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003408 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003409 }
3410}
3411/* Process `cmd` - copy contents until "`" is seen. Complicated by
3412 * \` quoting.
3413 * "Within the backquoted style of command substitution, backslash
3414 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3415 * The search for the matching backquote shall be satisfied by the first
3416 * backquote found without a preceding backslash; during this search,
3417 * if a non-escaped backquote is encountered within a shell comment,
3418 * a here-document, an embedded command substitution of the $(command)
3419 * form, or a quoted string, undefined results occur. A single-quoted
3420 * or double-quoted string that begins, but does not end, within the
3421 * "`...`" sequence produces undefined results."
3422 * Example Output
3423 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3424 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003425static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003426{
3427 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003428 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003429 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003430 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003431 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003432 }
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 == '\\') {
3436 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003437 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003438 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003439 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003440 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003441 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003442 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003443 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003444 ch = ch2;
3445 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003446 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003447 }
3448}
3449/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3450 * quoting and nested ()s.
3451 * "With the $(command) style of command substitution, all characters
3452 * following the open parenthesis to the matching closing parenthesis
3453 * constitute the command. Any valid shell script can be used for command,
3454 * except a script consisting solely of redirections which produces
3455 * unspecified results."
3456 * Example Output
3457 * echo $(echo '(TEST)' BEST) (TEST) BEST
3458 * echo $(echo 'TEST)' BEST) TEST) BEST
3459 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003460 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003461 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003462 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003463 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3464 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003465 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003466#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003467static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003468{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003469 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003470 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003471# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003472 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003473# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003474 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3475
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003476 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003477 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003478 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003479 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003480 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003481 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003482 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003483 if (!dbl)
3484 break;
3485 /* we look for closing )) of $((EXPR)) */
3486 if (i_peek(input) == end_ch) {
3487 i_getch(input); /* eat second ')' */
3488 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003489 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003490 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003491 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003492 if (ch == '(' || ch == '{') {
3493 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003494 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003495 o_addchr(dest, ch);
3496 continue;
3497 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003498 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003499 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003500 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003501 continue;
3502 }
3503 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003504 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003505 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003506 continue;
3507 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003508 if (ch == '`') {
3509 add_till_backquote(dest, input);
3510 o_addchr(dest, ch);
3511 continue;
3512 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003513 if (ch == '\\') {
3514 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003515 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003516 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003517 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003518 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003519 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003520 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003521 continue;
3522 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003523 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003524 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003525}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003526#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003527
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003528/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003529#if BB_MMU
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003530#define parse_dollar(as_string, dest, input) \
3531 parse_dollar(dest, input)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003532#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003533#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003534static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003535 o_string *dest,
3536 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003537{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003538 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003539 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003540
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003541 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003542 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003543 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003544 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003545 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003546 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003547 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003548 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003549 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003550 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003551 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003552 if (!isalnum(ch) && ch != '_')
3553 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003554 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003555 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003556 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003557 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003558 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003559 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003560 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003561 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003562 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003563 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003564 o_addchr(dest, ch | quote_mask);
3565 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003566 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003567 case '$': /* pid */
3568 case '!': /* last bg pid */
3569 case '?': /* last exit code */
3570 case '#': /* number of args */
3571 case '*': /* args */
3572 case '@': /* args */
3573 goto make_one_char_var;
3574 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003575 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3576
Denys Vlasenko74369502010-05-21 19:52:01 +02003577 ch = i_getch(input); /* eat '{' */
3578 nommu_addchr(as_string, ch);
3579
3580 ch = i_getch(input); /* first char after '{' */
3581 nommu_addchr(as_string, ch);
3582 /* It should be ${?}, or ${#var},
3583 * or even ${?+subst} - operator acting on a special variable,
3584 * or the beginning of variable name.
3585 */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02003586 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
Denys Vlasenko74369502010-05-21 19:52:01 +02003587 bad_dollar_syntax:
3588 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003589 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003590 return 1;
3591 }
3592 ch |= quote_mask;
3593
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003594 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003595 * However, this regresses some of our testsuite cases
3596 * which check invalid constructs like ${%}.
3597 * Oh well... let's check that the var name part is fine... */
3598
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003599 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003600 unsigned pos;
3601
Denys Vlasenko74369502010-05-21 19:52:01 +02003602 o_addchr(dest, ch);
3603 debug_printf_parse(": '%c'\n", ch);
3604
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003605 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003606 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003607 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003608 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003609
Denys Vlasenko74369502010-05-21 19:52:01 +02003610 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003611 unsigned end_ch;
3612 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003613 /* handle parameter expansions
3614 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3615 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003616 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003617 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003618
3619 /* Eat everything until closing '}' (or ':') */
3620 end_ch = '}';
3621 if (ENABLE_HUSH_BASH_COMPAT
3622 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003623 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003624 ) {
3625 /* It's ${var:N[:M]} thing */
3626 end_ch = '}' * 0x100 + ':';
3627 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003628 if (ENABLE_HUSH_BASH_COMPAT
3629 && ch == '/'
3630 ) {
3631 /* It's ${var/[/]pattern[/repl]} thing */
3632 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3633 i_getch(input);
3634 nommu_addchr(as_string, '/');
3635 ch = '\\';
3636 }
3637 end_ch = '}' * 0x100 + '/';
3638 }
3639 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003640 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003641 if (!BB_MMU)
3642 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003643#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003644 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003645#else
3646#error Simple code to only allow ${var} is not implemented
3647#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003648 if (as_string) {
3649 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003650 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003651 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003652
3653 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3654 /* close the first block: */
3655 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003656 /* while parsing N from ${var:N[:M]}
3657 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003658 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003659 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003660 end_ch = '}';
3661 goto again;
3662 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003663 /* got '}' */
3664 if (end_ch == '}' * 0x100 + ':') {
3665 /* it's ${var:N} - emulate :999999999 */
3666 o_addstr(dest, "999999999");
3667 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003668 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003669 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003670 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003671 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3673 break;
3674 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003675#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003676 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003677 unsigned pos;
3678
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003679 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003680 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003681# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003682 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003683 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003684 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003685 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3686 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003687 if (!BB_MMU)
3688 pos = dest->length;
3689 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003690 if (as_string) {
3691 o_addstr(as_string, dest->data + pos);
3692 o_addchr(as_string, ')');
3693 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003694 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003695 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003696 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003697 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003698# endif
3699# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3701 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003702 if (!BB_MMU)
3703 pos = dest->length;
3704 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003705 if (as_string) {
3706 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003707 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003708 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003709 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003710# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003711 break;
3712 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003713#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003714 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003715 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003716 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003717 ch = i_peek(input);
3718 if (isalnum(ch)) { /* it's $_name or $_123 */
3719 ch = '_';
3720 goto make_var;
3721 }
3722 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003723 /* TODO: $_ and $-: */
3724 /* $_ Shell or shell script name; or last argument of last command
3725 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3726 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003727 /* $- Option flags set by set builtin or shell options (-i etc) */
3728 default:
3729 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003730 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003731 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003732 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003733#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003734}
3735
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003736#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003737#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003738 parse_stream_dquoted(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003739#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003740#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003741static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003742 o_string *dest,
3743 struct in_str *input,
3744 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003745{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003746 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003747 int next;
3748
3749 again:
3750 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003751 if (ch != EOF)
3752 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003753 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003754 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003755 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003756 debug_printf_parse("parse_stream_dquoted return 0\n");
3757 return 0;
3758 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003759 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003760 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003761 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003762 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003763 }
3764 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003765 if (ch != '\n') {
3766 next = i_peek(input);
3767 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003768 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003769 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003770 if (ch == '\\') {
3771 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003772 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003773 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003774 }
3775 /* bash:
3776 * "The backslash retains its special meaning [in "..."]
3777 * only when followed by one of the following characters:
3778 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003779 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003780 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02003781 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00003782 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02003783 if (ch != '\n') {
3784 o_addqchr(dest, ch);
3785 nommu_addchr(as_string, ch);
3786 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003787 } else {
3788 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00003789 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003790 }
3791 goto again;
3792 }
3793 if (ch == '$') {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003794 if (parse_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003795 debug_printf_parse("parse_stream_dquoted return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003796 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003797 return 1;
3798 }
3799 goto again;
3800 }
3801#if ENABLE_HUSH_TICK
3802 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003803 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003804 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3805 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003806 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003807 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3808 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003809 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003810 }
3811#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003812 o_addQchr(dest, ch);
3813 if (ch == '='
3814 && (dest->o_assignment == MAYBE_ASSIGNMENT
3815 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003816 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00003817 ) {
3818 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3819 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003820 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003821#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003822}
3823
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003824/*
3825 * Scan input until EOF or end_trigger char.
3826 * Return a list of pipes to execute, or NULL on EOF
3827 * or if end_trigger character is met.
3828 * On syntax error, exit is shell is not interactive,
3829 * reset parsing machinery and start parsing anew,
3830 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003831 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003832static struct pipe *parse_stream(char **pstring,
3833 struct in_str *input,
3834 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003835{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003836 struct parse_context ctx;
3837 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003838 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003839 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00003840
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003841 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00003842 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003843 * found. When recursing, quote state is passed in via dest->o_escape.
3844 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003845 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02003846 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003847 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003848
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003849 /* If very first arg is "" or '', dest.data may end up NULL.
3850 * Preventing this: */
3851 o_addchr(&dest, '\0');
3852 dest.length = 0;
3853
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003854 G.ifs = get_local_var_value("IFS");
3855 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01003856 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003857
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003858 reset:
3859#if ENABLE_HUSH_INTERACTIVE
3860 input->promptmode = 0; /* PS1 */
3861#endif
3862 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
3863 initialize_context(&ctx);
3864 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003865 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003866 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003867 const char *is_ifs;
3868 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003869 int ch;
3870 int next;
3871 int redir_fd;
3872 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003873
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003874 if (is_in_dquote) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003875 /* dest.has_quoted_part = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003876 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003877 goto parse_error;
3878 }
3879 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003880 is_in_dquote = 0;
3881 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003882 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003883 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3884 ch, ch, dest.o_escape);
3885 if (ch == EOF) {
3886 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003887
3888 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003889 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003890 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003891 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003892 /* end_trigger == '}' case errors out earlier,
3893 * checking only ')' */
3894 if (end_trigger == ')') {
3895 syntax_error_unterm_ch('('); /* exits */
3896 /* goto parse_error; */
3897 }
3898
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003899 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003900 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003901 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003902 o_free(&dest);
3903 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003904 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003905 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003906 /* (this makes bare "&" cmd a no-op.
3907 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003908 if (pi->num_cmds == 0
3909 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3910 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003911 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003912 pi = NULL;
3913 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003914#if !BB_MMU
3915 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3916 if (pstring)
3917 *pstring = ctx.as_string.data;
3918 else
3919 o_free_unsafe(&ctx.as_string);
3920#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003921 debug_leave();
3922 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003923 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003924 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003925 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003926
3927 next = '\0';
3928 if (ch != '\n')
3929 next = i_peek(input);
3930
3931 is_special = "{}<>;&|()#'" /* special outside of "str" */
3932 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3933 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003934 if (ctx.command->argv /* word [word]{... - non-special */
3935 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003936 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003937 || (next != ';' /* }; - special */
3938 && next != ')' /* }) - special */
3939 && next != '&' /* }& and }&& ... - special */
3940 && next != '|' /* }|| ... - special */
3941 && !strchr(G.ifs, next) /* {word - non-special */
3942 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003943 ) {
3944 /* They are not special, skip "{}" */
3945 is_special += 2;
3946 }
3947 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003948 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003949
3950 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003951 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003952 o_addQchr(&dest, ch);
3953 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3954 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003955 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003956 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00003957 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003958 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003959 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003960 continue;
3961 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00003962
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003963 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003964 if (done_word(&dest, &ctx)) {
3965 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00003966 }
Denis Vlasenko37181682009-04-03 03:19:15 +00003967 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003968#if ENABLE_HUSH_CASE
3969 /* "case ... in <newline> word) ..." -
3970 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003971 if (ctx.command->argv == NULL
3972 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00003973 ) {
3974 continue;
3975 }
3976#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003977 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003978 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003979 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3980 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003981 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003982 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003983 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003984 heredoc_cnt = 0;
3985 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003986 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003987 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00003988 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003989 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003990 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003991 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00003992
3993 /* "cmd}" or "cmd }..." without semicolon or &:
3994 * } is an ordinary char in this case, even inside { cmd; }
3995 * Pathological example: { ""}; } should exec "}" cmd
3996 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00003997 if (ch == '}') {
3998 if (!IS_NULL_CMD(ctx.command) /* cmd } */
3999 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004000 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004001 ) {
4002 goto ordinary_char;
4003 }
4004 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4005 goto skip_end_trigger;
4006 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004007 }
4008
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004009 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004010 && (ch != ';' || heredoc_cnt == 0)
4011#if ENABLE_HUSH_CASE
4012 && (ch != ')'
4013 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004014 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004015 )
4016#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004017 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004018 if (heredoc_cnt) {
4019 /* This is technically valid:
4020 * { cat <<HERE; }; echo Ok
4021 * heredoc
4022 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004023 * HERE
4024 * but we don't support this.
4025 * We require heredoc to be in enclosing {}/(),
4026 * if any.
4027 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004028 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004029 goto parse_error;
4030 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004031 if (done_word(&dest, &ctx)) {
4032 goto parse_error;
4033 }
4034 done_pipe(&ctx, PIPE_SEQ);
4035 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004036 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004037 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004038 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004039 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004040 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004041#if !BB_MMU
4042 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4043 if (pstring)
4044 *pstring = ctx.as_string.data;
4045 else
4046 o_free_unsafe(&ctx.as_string);
4047#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004048 debug_leave();
4049 debug_printf_parse("parse_stream return %p: "
4050 "end_trigger char found\n",
4051 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004052 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004053 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004054 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004055 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004056 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004057 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004058
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004059 /* Catch <, > before deciding whether this word is
4060 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4061 switch (ch) {
4062 case '>':
4063 redir_fd = redirect_opt_num(&dest);
4064 if (done_word(&dest, &ctx)) {
4065 goto parse_error;
4066 }
4067 redir_style = REDIRECT_OVERWRITE;
4068 if (next == '>') {
4069 redir_style = REDIRECT_APPEND;
4070 ch = i_getch(input);
4071 nommu_addchr(&ctx.as_string, ch);
4072 }
4073#if 0
4074 else if (next == '(') {
4075 syntax_error(">(process) not supported");
4076 goto parse_error;
4077 }
4078#endif
4079 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4080 goto parse_error;
4081 continue; /* back to top of while (1) */
4082 case '<':
4083 redir_fd = redirect_opt_num(&dest);
4084 if (done_word(&dest, &ctx)) {
4085 goto parse_error;
4086 }
4087 redir_style = REDIRECT_INPUT;
4088 if (next == '<') {
4089 redir_style = REDIRECT_HEREDOC;
4090 heredoc_cnt++;
4091 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4092 ch = i_getch(input);
4093 nommu_addchr(&ctx.as_string, ch);
4094 } else if (next == '>') {
4095 redir_style = REDIRECT_IO;
4096 ch = i_getch(input);
4097 nommu_addchr(&ctx.as_string, ch);
4098 }
4099#if 0
4100 else if (next == '(') {
4101 syntax_error("<(process) not supported");
4102 goto parse_error;
4103 }
4104#endif
4105 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4106 goto parse_error;
4107 continue; /* back to top of while (1) */
4108 }
4109
4110 if (dest.o_assignment == MAYBE_ASSIGNMENT
4111 /* check that we are not in word in "a=1 2>word b=1": */
4112 && !ctx.pending_redirect
4113 ) {
4114 /* ch is a special char and thus this word
4115 * cannot be an assignment */
4116 dest.o_assignment = NOT_ASSIGNMENT;
4117 }
4118
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004119 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4120
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004121 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00004122 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004123 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004124 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004125 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004126 if (ch == EOF || ch == '\n')
4127 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004128 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004129 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004130 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004131 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00004132 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004133 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004134 }
4135 break;
4136 case '\\':
4137 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004138 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004139 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004140 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004141 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004142 if (ch != '\n') {
4143 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004144 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004145 o_addchr(&dest, ch);
4146 nommu_addchr(&ctx.as_string, ch);
4147 /* Example: echo Hello \2>file
4148 * we need to know that word 2 is quoted */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004149 dest.has_quoted_part = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004150 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004151#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004152 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004153 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4154 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004155 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02004156#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004157 break;
4158 case '$':
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004159 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004160 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004161 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004162 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004163 }
Eric Andersen25f27032001-04-26 23:22:31 +00004164 break;
4165 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004166 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004167 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004168 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004169 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004170 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004171 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004172 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004173 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004174 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004175 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004176 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004177 }
Eric Andersen25f27032001-04-26 23:22:31 +00004178 break;
4179 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004180 dest.has_quoted_part = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004181 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004182 if (dest.o_assignment == NOT_ASSIGNMENT)
4183 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004184 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004185#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004186 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004187 unsigned pos;
4188
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004189 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4190 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004191 pos = dest.length;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004192 add_till_backquote(&dest, input);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004193# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004194 o_addstr(&ctx.as_string, dest.data + pos);
4195 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004196# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004197 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4198 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004199 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004200 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004201#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004202 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004203#if ENABLE_HUSH_CASE
4204 case_semi:
4205#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004206 if (done_word(&dest, &ctx)) {
4207 goto parse_error;
4208 }
4209 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004210#if ENABLE_HUSH_CASE
4211 /* Eat multiple semicolons, detect
4212 * whether it means something special */
4213 while (1) {
4214 ch = i_peek(input);
4215 if (ch != ';')
4216 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004217 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004218 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004219 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004220 ctx.ctx_dsemicolon = 1;
4221 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004222 break;
4223 }
4224 }
4225#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004226 new_cmd:
4227 /* We just finished a cmd. New one may start
4228 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004229 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004230 break;
4231 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004232 if (done_word(&dest, &ctx)) {
4233 goto parse_error;
4234 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004235 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004236 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004237 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004238 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004239 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004240 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004241 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004242 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004243 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004244 if (done_word(&dest, &ctx)) {
4245 goto parse_error;
4246 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004247#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004248 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004249 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004250#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004251 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004252 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004253 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004254 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004255 } else {
4256 /* we could pick up a file descriptor choice here
4257 * with redirect_opt_num(), but bash doesn't do it.
4258 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004259 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004260#if !BB_MMU
4261 o_reset_to_empty_unquoted(&ctx.as_string);
4262#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004263 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004264 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004265 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004266#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004267 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004268 if (ctx.ctx_res_w == RES_MATCH
4269 && ctx.command->argv == NULL /* not (word|(... */
4270 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004271 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004272 ) {
4273 continue;
4274 }
4275#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004276 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004277 if (parse_group(&dest, &ctx, input, ch) != 0) {
4278 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004279 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004280 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004281 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004282#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004283 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004284 goto case_semi;
4285#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004286 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004287 /* proper use of this character is caught by end_trigger:
4288 * if we see {, we call parse_group(..., end_trigger='}')
4289 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004290 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004291 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004292 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004293 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004294 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004295 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004296 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004297
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004298 parse_error:
4299 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004300 struct parse_context *pctx;
4301 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004302
4303 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004304 * Sample for finding leaks on syntax error recovery path.
4305 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004306 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004307 * Samples to catch leaks at execution:
4308 * while if (true | {true;}); then echo ok; fi; do break; done
4309 * 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 +00004310 */
4311 pctx = &ctx;
4312 do {
4313 /* Update pipe/command counts,
4314 * otherwise freeing may miss some */
4315 done_pipe(pctx, PIPE_SEQ);
4316 debug_printf_clean("freeing list %p from ctx %p\n",
4317 pctx->list_head, pctx);
4318 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004319 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004320 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004321#if !BB_MMU
4322 o_free_unsafe(&pctx->as_string);
4323#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004324 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004325 if (pctx != &ctx) {
4326 free(pctx);
4327 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004328 IF_HAS_KEYWORDS(pctx = p2;)
4329 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004330 /* Free text, clear all dest fields */
4331 o_free(&dest);
4332 /* If we are not in top-level parse, we return,
4333 * our caller will propagate error.
4334 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004335 if (end_trigger != ';') {
4336#if !BB_MMU
4337 if (pstring)
4338 *pstring = NULL;
4339#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004340 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004341 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004342 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004343 /* Discard cached input, force prompt */
4344 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004345 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004346 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004347 }
Eric Andersen25f27032001-04-26 23:22:31 +00004348}
4349
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004350
4351/*** Execution routines ***/
4352
4353/* Expansion can recurse, need forward decls: */
4354static char *expand_string_to_string(const char *str);
4355static int process_command_subs(o_string *dest, const char *s);
4356
4357/* expand_strvec_to_strvec() takes a list of strings, expands
4358 * all variable references within and returns a pointer to
4359 * a list of expanded strings, possibly with larger number
4360 * of strings. (Think VAR="a b"; echo $VAR).
4361 * This new list is allocated as a single malloc block.
4362 * NULL-terminated list of char* pointers is at the beginning of it,
4363 * followed by strings themself.
4364 * Caller can deallocate entire list by single free(list). */
4365
4366/* Store given string, finalizing the word and starting new one whenever
4367 * we encounter IFS char(s). This is used for expanding variable values.
4368 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4369static int expand_on_ifs(o_string *output, int n, const char *str)
4370{
4371 while (1) {
4372 int word_len = strcspn(str, G.ifs);
4373 if (word_len) {
4374 if (output->o_escape || !output->o_glob)
4375 o_addQblock(output, str, word_len);
4376 else /* protect backslashes against globbing up :) */
4377 o_addblock_duplicate_backslash(output, str, word_len);
4378 str += word_len;
4379 }
4380 if (!*str) /* EOL - do not finalize word */
4381 break;
4382 o_addchr(output, '\0');
4383 debug_print_list("expand_on_ifs", output, n);
4384 n = o_save_ptr(output, n);
4385 str += strspn(str, G.ifs); /* skip ifs chars */
4386 }
4387 debug_print_list("expand_on_ifs[1]", output, n);
4388 return n;
4389}
4390
4391/* Helper to expand $((...)) and heredoc body. These act as if
4392 * they are in double quotes, with the exception that they are not :).
4393 * Just the rules are similar: "expand only $var and `cmd`"
4394 *
4395 * Returns malloced string.
4396 * As an optimization, we return NULL if expansion is not needed.
4397 */
4398static char *expand_pseudo_dquoted(const char *str)
4399{
4400 char *exp_str;
4401 struct in_str input;
4402 o_string dest = NULL_O_STRING;
4403
4404 if (!strchr(str, '$')
4405#if ENABLE_HUSH_TICK
4406 && !strchr(str, '`')
4407#endif
4408 ) {
4409 return NULL;
4410 }
4411
4412 /* We need to expand. Example:
4413 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4414 */
4415 setup_string_in_str(&input, str);
4416 parse_stream_dquoted(NULL, &dest, &input, EOF);
4417 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4418 exp_str = expand_string_to_string(dest.data);
4419 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4420 o_free_unsafe(&dest);
4421 return exp_str;
4422}
4423
4424#if ENABLE_SH_MATH_SUPPORT
4425static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
4426{
4427 arith_eval_hooks_t hooks;
4428 arith_t res;
4429 char *exp_str;
4430
4431 hooks.lookupvar = get_local_var_value;
4432 hooks.setvar = set_local_var_from_halves;
4433 hooks.endofname = endofname;
4434 exp_str = expand_pseudo_dquoted(arg);
4435 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
4436 free(exp_str);
4437 return res;
4438}
4439#endif
4440
4441#if ENABLE_HUSH_BASH_COMPAT
4442/* ${var/[/]pattern[/repl]} helpers */
4443static char *strstr_pattern(char *val, const char *pattern, int *size)
4444{
4445 while (1) {
4446 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4447 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4448 if (end) {
4449 *size = end - val;
4450 return val;
4451 }
4452 if (*val == '\0')
4453 return NULL;
4454 /* Optimization: if "*pat" did not match the start of "string",
4455 * we know that "tring", "ring" etc will not match too:
4456 */
4457 if (pattern[0] == '*')
4458 return NULL;
4459 val++;
4460 }
4461}
4462static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4463{
4464 char *result = NULL;
4465 unsigned res_len = 0;
4466 unsigned repl_len = strlen(repl);
4467
4468 while (1) {
4469 int size;
4470 char *s = strstr_pattern(val, pattern, &size);
4471 if (!s)
4472 break;
4473
4474 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4475 memcpy(result + res_len, val, s - val);
4476 res_len += s - val;
4477 strcpy(result + res_len, repl);
4478 res_len += repl_len;
4479 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4480
4481 val = s + size;
4482 if (exp_op == '/')
4483 break;
4484 }
4485 if (val[0] && result) {
4486 result = xrealloc(result, res_len + strlen(val) + 1);
4487 strcpy(result + res_len, val);
4488 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4489 }
4490 debug_printf_varexp("result:'%s'\n", result);
4491 return result;
4492}
4493#endif
4494
4495/* Helper:
4496 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4497 */
4498static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp, char first_ch)
4499{
4500 const char *val = NULL;
4501 char *to_be_freed = NULL;
4502 char *p = *pp;
4503 char *var;
4504 char first_char;
4505 char exp_op;
4506 char exp_save = exp_save; /* for compiler */
4507 char *exp_saveptr; /* points to expansion operator */
4508 char *exp_word = exp_word; /* for compiler */
4509
4510 var = arg;
4511 *p = '\0';
4512 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4513 first_char = arg[0] = first_ch & 0x7f;
4514 exp_op = 0;
4515
4516 if (first_char == '#' && arg[1] && !exp_saveptr) {
4517 /* handle length expansion ${#var} */
4518 var++;
4519 exp_op = 'L';
4520 } else {
4521 /* maybe handle parameter expansion */
4522 if (exp_saveptr /* if 2nd char is one of expansion operators */
4523 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4524 ) {
4525 /* ${?:0}, ${#[:]%0} etc */
4526 exp_saveptr = var + 1;
4527 } else {
4528 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4529 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4530 }
4531 exp_op = exp_save = *exp_saveptr;
4532 if (exp_op) {
4533 exp_word = exp_saveptr + 1;
4534 if (exp_op == ':') {
4535 exp_op = *exp_word++;
4536 if (ENABLE_HUSH_BASH_COMPAT
4537 && (exp_op == '\0' || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4538 ) {
4539 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4540 exp_op = ':';
4541 exp_word--;
4542 }
4543 }
4544 *exp_saveptr = '\0';
4545 } /* else: it's not an expansion op, but bare ${var} */
4546 }
4547
4548 /* lookup the variable in question */
4549 if (isdigit(var[0])) {
4550 /* parse_dollar() should have vetted var for us */
4551 int n = xatoi_positive(var);
4552 if (n < G.global_argc)
4553 val = G.global_argv[n];
4554 /* else val remains NULL: $N with too big N */
4555 } else {
4556 switch (var[0]) {
4557 case '$': /* pid */
4558 val = utoa(G.root_pid);
4559 break;
4560 case '!': /* bg pid */
4561 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4562 break;
4563 case '?': /* exitcode */
4564 val = utoa(G.last_exitcode);
4565 break;
4566 case '#': /* argc */
4567 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4568 break;
4569 default:
4570 val = get_local_var_value(var);
4571 }
4572 }
4573
4574 /* Handle any expansions */
4575 if (exp_op == 'L') {
4576 debug_printf_expand("expand: length(%s)=", val);
4577 val = utoa(val ? strlen(val) : 0);
4578 debug_printf_expand("%s\n", val);
4579 } else if (exp_op) {
4580 if (exp_op == '%' || exp_op == '#') {
4581 /* Standard-mandated substring removal ops:
4582 * ${parameter%word} - remove smallest suffix pattern
4583 * ${parameter%%word} - remove largest suffix pattern
4584 * ${parameter#word} - remove smallest prefix pattern
4585 * ${parameter##word} - remove largest prefix pattern
4586 *
4587 * Word is expanded to produce a glob pattern.
4588 * Then var's value is matched to it and matching part removed.
4589 */
4590 if (val && val[0]) {
4591 char *exp_exp_word;
4592 char *loc;
4593 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4594 if (exp_op == *exp_word) /* ## or %% */
4595 exp_word++;
4596//TODO: avoid xstrdup unless needed
4597// (see HACK ALERT below)
4598 val = to_be_freed = xstrdup(val);
4599 exp_exp_word = expand_pseudo_dquoted(exp_word);
4600 if (exp_exp_word)
4601 exp_word = exp_exp_word;
4602 loc = scan_and_match(to_be_freed, exp_word, scan_flags);
4603 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4604 // exp_op, to_be_freed, exp_word, loc);
4605 free(exp_exp_word);
4606 if (loc) { /* match was found */
4607 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4608 val = loc;
4609 else /* %[%] */
4610 *loc = '\0';
4611 }
4612 }
4613 }
4614#if ENABLE_HUSH_BASH_COMPAT
4615 else if (exp_op == '/' || exp_op == '\\') {
4616 /* Empty variable always gives nothing: */
4617 // "v=''; echo ${v/*/w}" prints ""
4618 if (val && val[0]) {
4619 /* It's ${var/[/]pattern[/repl]} thing */
4620 char *pattern, *repl, *t;
4621 pattern = expand_pseudo_dquoted(exp_word);
4622 if (!pattern)
4623 pattern = xstrdup(exp_word);
4624 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4625 *p++ = SPECIAL_VAR_SYMBOL;
4626 exp_word = p;
4627 p = strchr(p, SPECIAL_VAR_SYMBOL);
4628 *p = '\0';
4629 repl = expand_pseudo_dquoted(exp_word);
4630 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4631 /* HACK ALERT. We depend here on the fact that
4632 * G.global_argv and results of utoa and get_local_var_value
4633 * are actually in writable memory:
4634 * replace_pattern momentarily stores NULs there. */
4635 t = (char*)val;
4636 to_be_freed = replace_pattern(t,
4637 pattern,
4638 (repl ? repl : exp_word),
4639 exp_op);
4640 if (to_be_freed) /* at least one replace happened */
4641 val = to_be_freed;
4642 free(pattern);
4643 free(repl);
4644 }
4645 }
4646#endif
4647 else if (exp_op == ':') {
4648#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4649 /* It's ${var:N[:M]} bashism.
4650 * Note that in encoded form it has TWO parts:
4651 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4652 */
4653 arith_t beg, len;
4654 int errcode = 0;
4655
4656 beg = expand_and_evaluate_arith(exp_word, &errcode);
4657 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4658 *p++ = SPECIAL_VAR_SYMBOL;
4659 exp_word = p;
4660 p = strchr(p, SPECIAL_VAR_SYMBOL);
4661 *p = '\0';
4662 len = expand_and_evaluate_arith(exp_word, &errcode);
4663 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4664
4665 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
4666 if (beg < 0) /* bash compat */
4667 beg = 0;
4668 debug_printf_varexp("from val:'%s'\n", val);
4669 if (len == 0 || !val || beg >= strlen(val))
4670 val = "";
4671 else {
4672 /* Paranoia. What if user entered 9999999999999
4673 * which fits in arith_t but not int? */
4674 if (len >= INT_MAX)
4675 len = INT_MAX;
4676 val = to_be_freed = xstrndup(val + beg, len);
4677 }
4678 debug_printf_varexp("val:'%s'\n", val);
4679 } else
4680#endif
4681 {
4682 die_if_script("malformed ${%s:...}", var);
4683 val = "";
4684 }
4685 } else { /* one of "-=+?" */
4686 /* Standard-mandated substitution ops:
4687 * ${var?word} - indicate error if unset
4688 * If var is unset, word (or a message indicating it is unset
4689 * if word is null) is written to standard error
4690 * and the shell exits with a non-zero exit status.
4691 * Otherwise, the value of var is substituted.
4692 * ${var-word} - use default value
4693 * If var is unset, word is substituted.
4694 * ${var=word} - assign and use default value
4695 * If var is unset, word is assigned to var.
4696 * In all cases, final value of var is substituted.
4697 * ${var+word} - use alternative value
4698 * If var is unset, null is substituted.
4699 * Otherwise, word is substituted.
4700 *
4701 * Word is subjected to tilde expansion, parameter expansion,
4702 * command substitution, and arithmetic expansion.
4703 * If word is not needed, it is not expanded.
4704 *
4705 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4706 * but also treat null var as if it is unset.
4707 */
4708 int use_word = (!val || ((exp_save == ':') && !val[0]));
4709 if (exp_op == '+')
4710 use_word = !use_word;
4711 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4712 (exp_save == ':') ? "true" : "false", use_word);
4713 if (use_word) {
4714 to_be_freed = expand_pseudo_dquoted(exp_word);
4715 if (to_be_freed)
4716 exp_word = to_be_freed;
4717 if (exp_op == '?') {
4718 /* mimic bash message */
4719 die_if_script("%s: %s",
4720 var,
4721 exp_word[0] ? exp_word : "parameter null or not set"
4722 );
4723//TODO: how interactive bash aborts expansion mid-command?
4724 } else {
4725 val = exp_word;
4726 }
4727
4728 if (exp_op == '=') {
4729 /* ${var=[word]} or ${var:=[word]} */
4730 if (isdigit(var[0]) || var[0] == '#') {
4731 /* mimic bash message */
4732 die_if_script("$%s: cannot assign in this way", var);
4733 val = NULL;
4734 } else {
4735 char *new_var = xasprintf("%s=%s", var, val);
4736 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4737 }
4738 }
4739 }
4740 } /* one of "-=+?" */
4741
4742 *exp_saveptr = exp_save;
4743 } /* if (exp_op) */
4744
4745 arg[0] = first_ch;
4746
4747 *pp = p;
4748 *to_be_freed_pp = to_be_freed;
4749 return val;
4750}
4751
4752/* Expand all variable references in given string, adding words to list[]
4753 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4754 * to be filled). This routine is extremely tricky: has to deal with
4755 * variables/parameters with whitespace, $* and $@, and constructs like
4756 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4757static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
4758{
4759 /* or_mask is either 0 (normal case) or 0x80 -
4760 * expansion of right-hand side of assignment == 1-element expand.
4761 * It will also do no globbing, and thus we must not backslash-quote!
4762 */
4763 char ored_ch;
4764 char *p;
4765
4766 ored_ch = 0;
4767
4768 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
4769 debug_print_list("expand_vars_to_list", output, n);
4770 n = o_save_ptr(output, n);
4771 debug_print_list("expand_vars_to_list[0]", output, n);
4772
4773 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4774 char first_ch;
4775 int i;
4776 char *to_be_freed = NULL;
4777 const char *val = NULL;
4778#if ENABLE_HUSH_TICK
4779 o_string subst_result = NULL_O_STRING;
4780#endif
4781#if ENABLE_SH_MATH_SUPPORT
4782 char arith_buf[sizeof(arith_t)*3 + 2];
4783#endif
4784 o_addblock(output, arg, p - arg);
4785 debug_print_list("expand_vars_to_list[1]", output, n);
4786 arg = ++p;
4787 p = strchr(p, SPECIAL_VAR_SYMBOL);
4788
4789 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
4790 /* "$@" is special. Even if quoted, it can still
4791 * expand to nothing (not even an empty string) */
4792 if ((first_ch & 0x7f) != '@')
4793 ored_ch |= first_ch;
4794
4795 switch (first_ch & 0x7f) {
4796 /* Highest bit in first_ch indicates that var is double-quoted */
4797 case '*':
4798 case '@':
4799 i = 1;
4800 if (!G.global_argv[i])
4801 break;
4802 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4803 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4804 smallint sv = output->o_escape;
4805 /* unquoted var's contents should be globbed, so don't escape */
4806 output->o_escape = 0;
4807 while (G.global_argv[i]) {
4808 n = expand_on_ifs(output, n, G.global_argv[i]);
4809 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4810 if (G.global_argv[i++][0] && G.global_argv[i]) {
4811 /* this argv[] is not empty and not last:
4812 * put terminating NUL, start new word */
4813 o_addchr(output, '\0');
4814 debug_print_list("expand_vars_to_list[2]", output, n);
4815 n = o_save_ptr(output, n);
4816 debug_print_list("expand_vars_to_list[3]", output, n);
4817 }
4818 }
4819 output->o_escape = sv;
4820 } else
4821 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
4822 * and in this case should treat it like '$*' - see 'else...' below */
4823 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
4824 while (1) {
4825 o_addQstr(output, G.global_argv[i]);
4826 if (++i >= G.global_argc)
4827 break;
4828 o_addchr(output, '\0');
4829 debug_print_list("expand_vars_to_list[4]", output, n);
4830 n = o_save_ptr(output, n);
4831 }
4832 } else { /* quoted $*: add as one word */
4833 while (1) {
4834 o_addQstr(output, G.global_argv[i]);
4835 if (!G.global_argv[++i])
4836 break;
4837 if (G.ifs[0])
4838 o_addchr(output, G.ifs[0]);
4839 }
4840 }
4841 break;
4842 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4843 /* "Empty variable", used to make "" etc to not disappear */
4844 arg++;
4845 ored_ch = 0x80;
4846 break;
4847#if ENABLE_HUSH_TICK
4848 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4849 *p = '\0';
4850 arg++;
4851 /* Can't just stuff it into output o_string,
4852 * expanded result may need to be globbed
4853 * and $IFS-splitted */
4854 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4855 G.last_exitcode = process_command_subs(&subst_result, arg);
4856 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4857 val = subst_result.data;
4858 goto store_val;
4859#endif
4860#if ENABLE_SH_MATH_SUPPORT
4861 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4862 arith_t res;
4863 int errcode;
4864
4865 arg++; /* skip '+' */
4866 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4867 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4868 res = expand_and_evaluate_arith(arg, &errcode);
4869
4870 if (errcode < 0) {
4871 const char *msg = "error in arithmetic";
4872 switch (errcode) {
4873 case -3:
4874 msg = "exponent less than 0";
4875 break;
4876 case -2:
4877 msg = "divide by 0";
4878 break;
4879 case -5:
4880 msg = "expression recursion loop detected";
4881 break;
4882 }
4883 die_if_script(msg);
4884 }
4885 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
4886 sprintf(arith_buf, arith_t_fmt, res);
4887 val = arith_buf;
4888 break;
4889 }
4890#endif
4891 default:
4892 val = expand_one_var(&to_be_freed, arg, &p, first_ch);
4893 IF_HUSH_TICK(store_val:)
4894 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4895 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
4896 if (val && val[0]) {
4897 /* unquoted var's contents should be globbed, so don't escape */
4898 smallint sv = output->o_escape;
4899 output->o_escape = 0;
4900 n = expand_on_ifs(output, n, val);
4901 val = NULL;
4902 output->o_escape = sv;
4903 }
4904 } else { /* quoted $VAR, val will be appended below */
4905 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
4906 }
4907 break;
4908
4909 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4910
4911 if (val && val[0]) {
4912 o_addQstr(output, val);
4913 }
4914 free(to_be_freed);
4915 /* Do the check to avoid writing to a const string */
4916 if (*p != SPECIAL_VAR_SYMBOL)
4917 *p = SPECIAL_VAR_SYMBOL;
4918
4919#if ENABLE_HUSH_TICK
4920 o_free(&subst_result);
4921#endif
4922 arg = ++p;
4923 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4924
4925 if (arg[0]) {
4926 debug_print_list("expand_vars_to_list[a]", output, n);
4927 /* this part is literal, and it was already pre-quoted
4928 * if needed (much earlier), do not use o_addQstr here! */
4929 o_addstr_with_NUL(output, arg);
4930 debug_print_list("expand_vars_to_list[b]", output, n);
4931 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
4932 && !(ored_ch & 0x80) /* and all vars were not quoted. */
4933 ) {
4934 n--;
4935 /* allow to reuse list[n] later without re-growth */
4936 output->has_empty_slot = 1;
4937 } else {
4938 o_addchr(output, '\0');
4939 }
4940
4941 return n;
4942}
4943
4944enum {
4945 EXPVAR_FLAG_GLOB = 0x200,
4946 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
4947 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
4948};
4949static char **expand_variables(char **argv, unsigned or_mask)
4950{
4951 int n;
4952 char **list;
4953 char **v;
4954 o_string output = NULL_O_STRING;
4955
4956 /* protect against globbing for "$var"? */
4957 /* (unquoted $var will temporarily switch it off) */
4958 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
4959 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
4960
4961 n = 0;
4962 v = argv;
4963 while (*v) {
4964 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
4965 v++;
4966 }
4967 debug_print_list("expand_variables", &output, n);
4968
4969 /* output.data (malloced in one block) gets returned in "list" */
4970 list = o_finalize_list(&output, n);
4971 debug_print_strings("expand_variables[1]", list);
4972 return list;
4973}
4974
4975static char **expand_strvec_to_strvec(char **argv)
4976{
4977 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
4978}
4979
4980#if ENABLE_HUSH_BASH_COMPAT
4981static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
4982{
4983 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
4984}
4985#endif
4986
4987#ifdef CMD_SINGLEWORD_NOGLOB_COND
4988static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
4989{
4990 int n;
4991 char **list;
4992 char **v;
4993 o_string output = NULL_O_STRING;
4994
4995 n = 0;
4996 v = argv;
4997 while (*v) {
4998 int is_var = is_well_formed_var_name(*v, '=');
4999 /* is_var * 0x80: singleword expansion for vars */
5000 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
5001
5002 /* Subtle! expand_vars_to_list did not glob last word yet.
5003 * It does this only when fed with further data.
5004 * Therefore we set globbing flags AFTER it, not before:
5005 */
5006
5007 /* if it is not recognizably abc=...; then: */
5008 output.o_escape = !is_var; /* protect against globbing for "$var" */
5009 /* (unquoted $var will temporarily switch it off) */
5010 output.o_glob = !is_var; /* and indeed do globbing */
5011 v++;
5012 }
5013 debug_print_list("expand_cond", &output, n);
5014
5015 /* output.data (malloced in one block) gets returned in "list" */
5016 list = o_finalize_list(&output, n);
5017 debug_print_strings("expand_cond[1]", list);
5018 return list;
5019}
5020#endif
5021
5022/* Used for expansion of right hand of assignments */
5023/* NB: should NOT do globbing!
5024 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
5025static char *expand_string_to_string(const char *str)
5026{
5027 char *argv[2], **list;
5028
5029 /* This is generally an optimization, but it also
5030 * handles "", which otherwise trips over !list[0] check below.
5031 * (is this ever happens that we actually get str="" here?)
5032 */
5033 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5034 //TODO: Can use on strings with \ too, just unbackslash() them?
5035 debug_printf_expand("string_to_string(fast)='%s'\n", str);
5036 return xstrdup(str);
5037 }
5038
5039 argv[0] = (char*)str;
5040 argv[1] = NULL;
5041 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
5042 if (HUSH_DEBUG)
5043 if (!list[0] || list[1])
5044 bb_error_msg_and_die("BUG in varexp2");
5045 /* actually, just move string 2*sizeof(char*) bytes back */
5046 overlapping_strcpy((char*)list, list[0]);
5047 unbackslash((char*)list);
5048 debug_printf_expand("string_to_string='%s'\n", (char*)list);
5049 return (char*)list;
5050}
5051
5052/* Used for "eval" builtin */
5053static char* expand_strvec_to_string(char **argv)
5054{
5055 char **list;
5056
5057 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
5058 /* Convert all NULs to spaces */
5059 if (list[0]) {
5060 int n = 1;
5061 while (list[n]) {
5062 if (HUSH_DEBUG)
5063 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5064 bb_error_msg_and_die("BUG in varexp3");
5065 /* bash uses ' ' regardless of $IFS contents */
5066 list[n][-1] = ' ';
5067 n++;
5068 }
5069 }
5070 overlapping_strcpy((char*)list, list[0]);
5071 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5072 return (char*)list;
5073}
5074
5075static char **expand_assignments(char **argv, int count)
5076{
5077 int i;
5078 char **p;
5079
5080 G.expanded_assignments = p = NULL;
5081 /* Expand assignments into one string each */
5082 for (i = 0; i < count; i++) {
5083 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
5084 }
5085 G.expanded_assignments = NULL;
5086 return p;
5087}
5088
5089
5090#if BB_MMU
5091/* never called */
5092void re_execute_shell(char ***to_free, const char *s,
5093 char *g_argv0, char **g_argv,
5094 char **builtin_argv) NORETURN;
5095
5096static void reset_traps_to_defaults(void)
5097{
5098 /* This function is always called in a child shell
5099 * after fork (not vfork, NOMMU doesn't use this function).
5100 */
5101 unsigned sig;
5102 unsigned mask;
5103
5104 /* Child shells are not interactive.
5105 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5106 * Testcase: (while :; do :; done) + ^Z should background.
5107 * Same goes for SIGTERM, SIGHUP, SIGINT.
5108 */
5109 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5110 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5111
5112 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5113 * Stupid. It can be done with *single* &= op, but we can't use
5114 * the fact that G.blocked_set is implemented as a bitmask
5115 * in libc... */
5116 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5117 sig = 1;
5118 while (1) {
5119 if (mask & 1) {
5120 /* Careful. Only if no trap or trap is not "" */
5121 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5122 sigdelset(&G.blocked_set, sig);
5123 }
5124 mask >>= 1;
5125 if (!mask)
5126 break;
5127 sig++;
5128 }
5129 /* Our homegrown sig mask is saner to work with :) */
5130 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5131
5132 /* Resetting all traps to default except empty ones */
5133 mask = G.non_DFL_mask;
5134 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5135 if (!G.traps[sig] || !G.traps[sig][0])
5136 continue;
5137 free(G.traps[sig]);
5138 G.traps[sig] = NULL;
5139 /* There is no signal for 0 (EXIT) */
5140 if (sig == 0)
5141 continue;
5142 /* There was a trap handler, we just removed it.
5143 * But if sig still has non-DFL handling,
5144 * we should not unblock the sig. */
5145 if (mask & 1)
5146 continue;
5147 sigdelset(&G.blocked_set, sig);
5148 }
5149 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5150}
5151
5152#else /* !BB_MMU */
5153
5154static void re_execute_shell(char ***to_free, const char *s,
5155 char *g_argv0, char **g_argv,
5156 char **builtin_argv) NORETURN;
5157static void re_execute_shell(char ***to_free, const char *s,
5158 char *g_argv0, char **g_argv,
5159 char **builtin_argv)
5160{
5161# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5162 /* delims + 2 * (number of bytes in printed hex numbers) */
5163 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5164 char *heredoc_argv[4];
5165 struct variable *cur;
5166# if ENABLE_HUSH_FUNCTIONS
5167 struct function *funcp;
5168# endif
5169 char **argv, **pp;
5170 unsigned cnt;
5171 unsigned long long empty_trap_mask;
5172
5173 if (!g_argv0) { /* heredoc */
5174 argv = heredoc_argv;
5175 argv[0] = (char *) G.argv0_for_re_execing;
5176 argv[1] = (char *) "-<";
5177 argv[2] = (char *) s;
5178 argv[3] = NULL;
5179 pp = &argv[3]; /* used as pointer to empty environment */
5180 goto do_exec;
5181 }
5182
5183 cnt = 0;
5184 pp = builtin_argv;
5185 if (pp) while (*pp++)
5186 cnt++;
5187
5188 empty_trap_mask = 0;
5189 if (G.traps) {
5190 int sig;
5191 for (sig = 1; sig < NSIG; sig++) {
5192 if (G.traps[sig] && !G.traps[sig][0])
5193 empty_trap_mask |= 1LL << sig;
5194 }
5195 }
5196
5197 sprintf(param_buf, NOMMU_HACK_FMT
5198 , (unsigned) G.root_pid
5199 , (unsigned) G.root_ppid
5200 , (unsigned) G.last_bg_pid
5201 , (unsigned) G.last_exitcode
5202 , cnt
5203 , empty_trap_mask
5204 IF_HUSH_LOOPS(, G.depth_of_loop)
5205 );
5206# undef NOMMU_HACK_FMT
5207 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5208 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5209 */
5210 cnt += 6;
5211 for (cur = G.top_var; cur; cur = cur->next) {
5212 if (!cur->flg_export || cur->flg_read_only)
5213 cnt += 2;
5214 }
5215# if ENABLE_HUSH_FUNCTIONS
5216 for (funcp = G.top_func; funcp; funcp = funcp->next)
5217 cnt += 3;
5218# endif
5219 pp = g_argv;
5220 while (*pp++)
5221 cnt++;
5222 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5223 *pp++ = (char *) G.argv0_for_re_execing;
5224 *pp++ = param_buf;
5225 for (cur = G.top_var; cur; cur = cur->next) {
5226 if (strcmp(cur->varstr, hush_version_str) == 0)
5227 continue;
5228 if (cur->flg_read_only) {
5229 *pp++ = (char *) "-R";
5230 *pp++ = cur->varstr;
5231 } else if (!cur->flg_export) {
5232 *pp++ = (char *) "-V";
5233 *pp++ = cur->varstr;
5234 }
5235 }
5236# if ENABLE_HUSH_FUNCTIONS
5237 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5238 *pp++ = (char *) "-F";
5239 *pp++ = funcp->name;
5240 *pp++ = funcp->body_as_string;
5241 }
5242# endif
5243 /* We can pass activated traps here. Say, -Tnn:trap_string
5244 *
5245 * However, POSIX says that subshells reset signals with traps
5246 * to SIG_DFL.
5247 * I tested bash-3.2 and it not only does that with true subshells
5248 * of the form ( list ), but with any forked children shells.
5249 * I set trap "echo W" WINCH; and then tried:
5250 *
5251 * { echo 1; sleep 20; echo 2; } &
5252 * while true; do echo 1; sleep 20; echo 2; break; done &
5253 * true | { echo 1; sleep 20; echo 2; } | cat
5254 *
5255 * In all these cases sending SIGWINCH to the child shell
5256 * did not run the trap. If I add trap "echo V" WINCH;
5257 * _inside_ group (just before echo 1), it works.
5258 *
5259 * I conclude it means we don't need to pass active traps here.
5260 * Even if we would use signal handlers instead of signal masking
5261 * in order to implement trap handling,
5262 * exec syscall below resets signals to SIG_DFL for us.
5263 */
5264 *pp++ = (char *) "-c";
5265 *pp++ = (char *) s;
5266 if (builtin_argv) {
5267 while (*++builtin_argv)
5268 *pp++ = *builtin_argv;
5269 *pp++ = (char *) "";
5270 }
5271 *pp++ = g_argv0;
5272 while (*g_argv)
5273 *pp++ = *g_argv++;
5274 /* *pp = NULL; - is already there */
5275 pp = environ;
5276
5277 do_exec:
5278 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5279 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5280 execve(bb_busybox_exec_path, argv, pp);
5281 /* Fallback. Useful for init=/bin/hush usage etc */
5282 if (argv[0][0] == '/')
5283 execve(argv[0], argv, pp);
5284 xfunc_error_retval = 127;
5285 bb_error_msg_and_die("can't re-execute the shell");
5286}
5287#endif /* !BB_MMU */
5288
5289
5290static int run_and_free_list(struct pipe *pi);
5291
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005292/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005293 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5294 * end_trigger controls how often we stop parsing
5295 * NUL: parse all, execute, return
5296 * ';': parse till ';' or newline, execute, repeat till EOF
5297 */
5298static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005299{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005300 /* Why we need empty flag?
5301 * An obscure corner case "false; ``; echo $?":
5302 * empty command in `` should still set $? to 0.
5303 * But we can't just set $? to 0 at the start,
5304 * this breaks "false; echo `echo $?`" case.
5305 */
5306 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005307 while (1) {
5308 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005309
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005310 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005311 if (!pipe_list) { /* EOF */
5312 if (empty)
5313 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005314 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005315 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005316 debug_print_tree(pipe_list, 0);
5317 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5318 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005319 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005320 }
Eric Andersen25f27032001-04-26 23:22:31 +00005321}
5322
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005323static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005324{
5325 struct in_str input;
5326 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005327 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005328}
5329
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005330static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005331{
Eric Andersen25f27032001-04-26 23:22:31 +00005332 struct in_str input;
5333 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005334 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005335}
5336
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005337#if ENABLE_HUSH_TICK
5338static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5339{
5340 pid_t pid;
5341 int channel[2];
5342# if !BB_MMU
5343 char **to_free = NULL;
5344# endif
5345
5346 xpipe(channel);
5347 pid = BB_MMU ? xfork() : xvfork();
5348 if (pid == 0) { /* child */
5349 disable_restore_tty_pgrp_on_exit();
5350 /* Process substitution is not considered to be usual
5351 * 'command execution'.
5352 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5353 */
5354 bb_signals(0
5355 + (1 << SIGTSTP)
5356 + (1 << SIGTTIN)
5357 + (1 << SIGTTOU)
5358 , SIG_IGN);
5359 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5360 close(channel[0]); /* NB: close _first_, then move fd! */
5361 xmove_fd(channel[1], 1);
5362 /* Prevent it from trying to handle ctrl-z etc */
5363 IF_HUSH_JOB(G.run_list_level = 1;)
5364 /* Awful hack for `trap` or $(trap).
5365 *
5366 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5367 * contains an example where "trap" is executed in a subshell:
5368 *
5369 * save_traps=$(trap)
5370 * ...
5371 * eval "$save_traps"
5372 *
5373 * Standard does not say that "trap" in subshell shall print
5374 * parent shell's traps. It only says that its output
5375 * must have suitable form, but then, in the above example
5376 * (which is not supposed to be normative), it implies that.
5377 *
5378 * bash (and probably other shell) does implement it
5379 * (traps are reset to defaults, but "trap" still shows them),
5380 * but as a result, "trap" logic is hopelessly messed up:
5381 *
5382 * # trap
5383 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5384 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5385 * # true | trap <--- trap is in subshell - no output (ditto)
5386 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5387 * trap -- 'echo Ho' SIGWINCH
5388 * # echo `(trap)` <--- in subshell in subshell - output
5389 * trap -- 'echo Ho' SIGWINCH
5390 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5391 * trap -- 'echo Ho' SIGWINCH
5392 *
5393 * The rules when to forget and when to not forget traps
5394 * get really complex and nonsensical.
5395 *
5396 * Our solution: ONLY bare $(trap) or `trap` is special.
5397 */
5398 s = skip_whitespace(s);
5399 if (strncmp(s, "trap", 4) == 0
5400 && skip_whitespace(s + 4)[0] == '\0'
5401 ) {
5402 static const char *const argv[] = { NULL, NULL };
5403 builtin_trap((char**)argv);
5404 exit(0); /* not _exit() - we need to fflush */
5405 }
5406# if BB_MMU
5407 reset_traps_to_defaults();
5408 parse_and_run_string(s);
5409 _exit(G.last_exitcode);
5410# else
5411 /* We re-execute after vfork on NOMMU. This makes this script safe:
5412 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5413 * huge=`cat BIG` # was blocking here forever
5414 * echo OK
5415 */
5416 re_execute_shell(&to_free,
5417 s,
5418 G.global_argv[0],
5419 G.global_argv + 1,
5420 NULL);
5421# endif
5422 }
5423
5424 /* parent */
5425 *pid_p = pid;
5426# if ENABLE_HUSH_FAST
5427 G.count_SIGCHLD++;
5428//bb_error_msg("[%d] fork in generate_stream_from_string:"
5429// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5430// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5431# endif
5432 enable_restore_tty_pgrp_on_exit();
5433# if !BB_MMU
5434 free(to_free);
5435# endif
5436 close(channel[1]);
5437 close_on_exec_on(channel[0]);
5438 return xfdopen_for_read(channel[0]);
5439}
5440
5441/* Return code is exit status of the process that is run. */
5442static int process_command_subs(o_string *dest, const char *s)
5443{
5444 FILE *fp;
5445 struct in_str pipe_str;
5446 pid_t pid;
5447 int status, ch, eol_cnt;
5448
5449 fp = generate_stream_from_string(s, &pid);
5450
5451 /* Now send results of command back into original context */
5452 setup_file_in_str(&pipe_str, fp);
5453 eol_cnt = 0;
5454 while ((ch = i_getch(&pipe_str)) != EOF) {
5455 if (ch == '\n') {
5456 eol_cnt++;
5457 continue;
5458 }
5459 while (eol_cnt) {
5460 o_addchr(dest, '\n');
5461 eol_cnt--;
5462 }
5463 o_addQchr(dest, ch);
5464 }
5465
5466 debug_printf("done reading from `cmd` pipe, closing it\n");
5467 fclose(fp);
5468 /* We need to extract exitcode. Test case
5469 * "true; echo `sleep 1; false` $?"
5470 * should print 1 */
5471 safe_waitpid(pid, &status, 0);
5472 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5473 return WEXITSTATUS(status);
5474}
5475#endif /* ENABLE_HUSH_TICK */
5476
5477
5478static void setup_heredoc(struct redir_struct *redir)
5479{
5480 struct fd_pair pair;
5481 pid_t pid;
5482 int len, written;
5483 /* the _body_ of heredoc (misleading field name) */
5484 const char *heredoc = redir->rd_filename;
5485 char *expanded;
5486#if !BB_MMU
5487 char **to_free;
5488#endif
5489
5490 expanded = NULL;
5491 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5492 expanded = expand_pseudo_dquoted(heredoc);
5493 if (expanded)
5494 heredoc = expanded;
5495 }
5496 len = strlen(heredoc);
5497
5498 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5499 xpiped_pair(pair);
5500 xmove_fd(pair.rd, redir->rd_fd);
5501
5502 /* Try writing without forking. Newer kernels have
5503 * dynamically growing pipes. Must use non-blocking write! */
5504 ndelay_on(pair.wr);
5505 while (1) {
5506 written = write(pair.wr, heredoc, len);
5507 if (written <= 0)
5508 break;
5509 len -= written;
5510 if (len == 0) {
5511 close(pair.wr);
5512 free(expanded);
5513 return;
5514 }
5515 heredoc += written;
5516 }
5517 ndelay_off(pair.wr);
5518
5519 /* Okay, pipe buffer was not big enough */
5520 /* Note: we must not create a stray child (bastard? :)
5521 * for the unsuspecting parent process. Child creates a grandchild
5522 * and exits before parent execs the process which consumes heredoc
5523 * (that exec happens after we return from this function) */
5524#if !BB_MMU
5525 to_free = NULL;
5526#endif
5527 pid = xvfork();
5528 if (pid == 0) {
5529 /* child */
5530 disable_restore_tty_pgrp_on_exit();
5531 pid = BB_MMU ? xfork() : xvfork();
5532 if (pid != 0)
5533 _exit(0);
5534 /* grandchild */
5535 close(redir->rd_fd); /* read side of the pipe */
5536#if BB_MMU
5537 full_write(pair.wr, heredoc, len); /* may loop or block */
5538 _exit(0);
5539#else
5540 /* Delegate blocking writes to another process */
5541 xmove_fd(pair.wr, STDOUT_FILENO);
5542 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5543#endif
5544 }
5545 /* parent */
5546#if ENABLE_HUSH_FAST
5547 G.count_SIGCHLD++;
5548//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5549#endif
5550 enable_restore_tty_pgrp_on_exit();
5551#if !BB_MMU
5552 free(to_free);
5553#endif
5554 close(pair.wr);
5555 free(expanded);
5556 wait(NULL); /* wait till child has died */
5557}
5558
5559/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5560 * and stderr if they are redirected. */
5561static int setup_redirects(struct command *prog, int squirrel[])
5562{
5563 int openfd, mode;
5564 struct redir_struct *redir;
5565
5566 for (redir = prog->redirects; redir; redir = redir->next) {
5567 if (redir->rd_type == REDIRECT_HEREDOC2) {
5568 /* rd_fd<<HERE case */
5569 if (squirrel && redir->rd_fd < 3
5570 && squirrel[redir->rd_fd] < 0
5571 ) {
5572 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5573 }
5574 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5575 * of the heredoc */
5576 debug_printf_parse("set heredoc '%s'\n",
5577 redir->rd_filename);
5578 setup_heredoc(redir);
5579 continue;
5580 }
5581
5582 if (redir->rd_dup == REDIRFD_TO_FILE) {
5583 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5584 char *p;
5585 if (redir->rd_filename == NULL) {
5586 /* Something went wrong in the parse.
5587 * Pretend it didn't happen */
5588 bb_error_msg("bug in redirect parse");
5589 continue;
5590 }
5591 mode = redir_table[redir->rd_type].mode;
5592 p = expand_string_to_string(redir->rd_filename);
5593 openfd = open_or_warn(p, mode);
5594 free(p);
5595 if (openfd < 0) {
5596 /* this could get lost if stderr has been redirected, but
5597 * bash and ash both lose it as well (though zsh doesn't!) */
5598//what the above comment tries to say?
5599 return 1;
5600 }
5601 } else {
5602 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5603 openfd = redir->rd_dup;
5604 }
5605
5606 if (openfd != redir->rd_fd) {
5607 if (squirrel && redir->rd_fd < 3
5608 && squirrel[redir->rd_fd] < 0
5609 ) {
5610 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5611 }
5612 if (openfd == REDIRFD_CLOSE) {
5613 /* "n>-" means "close me" */
5614 close(redir->rd_fd);
5615 } else {
5616 xdup2(openfd, redir->rd_fd);
5617 if (redir->rd_dup == REDIRFD_TO_FILE)
5618 close(openfd);
5619 }
5620 }
5621 }
5622 return 0;
5623}
5624
5625static void restore_redirects(int squirrel[])
5626{
5627 int i, fd;
5628 for (i = 0; i < 3; i++) {
5629 fd = squirrel[i];
5630 if (fd != -1) {
5631 /* We simply die on error */
5632 xmove_fd(fd, i);
5633 }
5634 }
5635}
5636
5637static char *find_in_path(const char *arg)
5638{
5639 char *ret = NULL;
5640 const char *PATH = get_local_var_value("PATH");
5641
5642 if (!PATH)
5643 return NULL;
5644
5645 while (1) {
5646 const char *end = strchrnul(PATH, ':');
5647 int sz = end - PATH; /* must be int! */
5648
5649 free(ret);
5650 if (sz != 0) {
5651 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5652 } else {
5653 /* We have xxx::yyyy in $PATH,
5654 * it means "use current dir" */
5655 ret = xstrdup(arg);
5656 }
5657 if (access(ret, F_OK) == 0)
5658 break;
5659
5660 if (*end == '\0') {
5661 free(ret);
5662 return NULL;
5663 }
5664 PATH = end + 1;
5665 }
5666
5667 return ret;
5668}
5669
5670static const struct built_in_command* find_builtin_helper(const char *name,
5671 const struct built_in_command *x,
5672 const struct built_in_command *end)
5673{
5674 while (x != end) {
5675 if (strcmp(name, x->b_cmd) != 0) {
5676 x++;
5677 continue;
5678 }
5679 debug_printf_exec("found builtin '%s'\n", name);
5680 return x;
5681 }
5682 return NULL;
5683}
5684static const struct built_in_command* find_builtin1(const char *name)
5685{
5686 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5687}
5688static const struct built_in_command* find_builtin(const char *name)
5689{
5690 const struct built_in_command *x = find_builtin1(name);
5691 if (x)
5692 return x;
5693 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5694}
5695
5696#if ENABLE_HUSH_FUNCTIONS
5697static struct function **find_function_slot(const char *name)
5698{
5699 struct function **funcpp = &G.top_func;
5700 while (*funcpp) {
5701 if (strcmp(name, (*funcpp)->name) == 0) {
5702 break;
5703 }
5704 funcpp = &(*funcpp)->next;
5705 }
5706 return funcpp;
5707}
5708
5709static const struct function *find_function(const char *name)
5710{
5711 const struct function *funcp = *find_function_slot(name);
5712 if (funcp)
5713 debug_printf_exec("found function '%s'\n", name);
5714 return funcp;
5715}
5716
5717/* Note: takes ownership on name ptr */
5718static struct function *new_function(char *name)
5719{
5720 struct function **funcpp = find_function_slot(name);
5721 struct function *funcp = *funcpp;
5722
5723 if (funcp != NULL) {
5724 struct command *cmd = funcp->parent_cmd;
5725 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5726 if (!cmd) {
5727 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5728 free(funcp->name);
5729 /* Note: if !funcp->body, do not free body_as_string!
5730 * This is a special case of "-F name body" function:
5731 * body_as_string was not malloced! */
5732 if (funcp->body) {
5733 free_pipe_list(funcp->body);
5734# if !BB_MMU
5735 free(funcp->body_as_string);
5736# endif
5737 }
5738 } else {
5739 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5740 cmd->argv[0] = funcp->name;
5741 cmd->group = funcp->body;
5742# if !BB_MMU
5743 cmd->group_as_string = funcp->body_as_string;
5744# endif
5745 }
5746 } else {
5747 debug_printf_exec("remembering new function '%s'\n", name);
5748 funcp = *funcpp = xzalloc(sizeof(*funcp));
5749 /*funcp->next = NULL;*/
5750 }
5751
5752 funcp->name = name;
5753 return funcp;
5754}
5755
5756static void unset_func(const char *name)
5757{
5758 struct function **funcpp = find_function_slot(name);
5759 struct function *funcp = *funcpp;
5760
5761 if (funcp != NULL) {
5762 debug_printf_exec("freeing function '%s'\n", funcp->name);
5763 *funcpp = funcp->next;
5764 /* funcp is unlinked now, deleting it.
5765 * Note: if !funcp->body, the function was created by
5766 * "-F name body", do not free ->body_as_string
5767 * and ->name as they were not malloced. */
5768 if (funcp->body) {
5769 free_pipe_list(funcp->body);
5770 free(funcp->name);
5771# if !BB_MMU
5772 free(funcp->body_as_string);
5773# endif
5774 }
5775 free(funcp);
5776 }
5777}
5778
5779# if BB_MMU
5780#define exec_function(to_free, funcp, argv) \
5781 exec_function(funcp, argv)
5782# endif
5783static void exec_function(char ***to_free,
5784 const struct function *funcp,
5785 char **argv) NORETURN;
5786static void exec_function(char ***to_free,
5787 const struct function *funcp,
5788 char **argv)
5789{
5790# if BB_MMU
5791 int n = 1;
5792
5793 argv[0] = G.global_argv[0];
5794 G.global_argv = argv;
5795 while (*++argv)
5796 n++;
5797 G.global_argc = n;
5798 /* On MMU, funcp->body is always non-NULL */
5799 n = run_list(funcp->body);
5800 fflush_all();
5801 _exit(n);
5802# else
5803 re_execute_shell(to_free,
5804 funcp->body_as_string,
5805 G.global_argv[0],
5806 argv + 1,
5807 NULL);
5808# endif
5809}
5810
5811static int run_function(const struct function *funcp, char **argv)
5812{
5813 int rc;
5814 save_arg_t sv;
5815 smallint sv_flg;
5816
5817 save_and_replace_G_args(&sv, argv);
5818
5819 /* "we are in function, ok to use return" */
5820 sv_flg = G.flag_return_in_progress;
5821 G.flag_return_in_progress = -1;
5822# if ENABLE_HUSH_LOCAL
5823 G.func_nest_level++;
5824# endif
5825
5826 /* On MMU, funcp->body is always non-NULL */
5827# if !BB_MMU
5828 if (!funcp->body) {
5829 /* Function defined by -F */
5830 parse_and_run_string(funcp->body_as_string);
5831 rc = G.last_exitcode;
5832 } else
5833# endif
5834 {
5835 rc = run_list(funcp->body);
5836 }
5837
5838# if ENABLE_HUSH_LOCAL
5839 {
5840 struct variable *var;
5841 struct variable **var_pp;
5842
5843 var_pp = &G.top_var;
5844 while ((var = *var_pp) != NULL) {
5845 if (var->func_nest_level < G.func_nest_level) {
5846 var_pp = &var->next;
5847 continue;
5848 }
5849 /* Unexport */
5850 if (var->flg_export)
5851 bb_unsetenv(var->varstr);
5852 /* Remove from global list */
5853 *var_pp = var->next;
5854 /* Free */
5855 if (!var->max_len)
5856 free(var->varstr);
5857 free(var);
5858 }
5859 G.func_nest_level--;
5860 }
5861# endif
5862 G.flag_return_in_progress = sv_flg;
5863
5864 restore_G_args(&sv, argv);
5865
5866 return rc;
5867}
5868#endif /* ENABLE_HUSH_FUNCTIONS */
5869
5870
5871#if BB_MMU
5872#define exec_builtin(to_free, x, argv) \
5873 exec_builtin(x, argv)
5874#else
5875#define exec_builtin(to_free, x, argv) \
5876 exec_builtin(to_free, argv)
5877#endif
5878static void exec_builtin(char ***to_free,
5879 const struct built_in_command *x,
5880 char **argv) NORETURN;
5881static void exec_builtin(char ***to_free,
5882 const struct built_in_command *x,
5883 char **argv)
5884{
5885#if BB_MMU
5886 int rcode = x->b_function(argv);
5887 fflush_all();
5888 _exit(rcode);
5889#else
5890 /* On NOMMU, we must never block!
5891 * Example: { sleep 99 | read line; } & echo Ok
5892 */
5893 re_execute_shell(to_free,
5894 argv[0],
5895 G.global_argv[0],
5896 G.global_argv + 1,
5897 argv);
5898#endif
5899}
5900
5901
5902static void execvp_or_die(char **argv) NORETURN;
5903static void execvp_or_die(char **argv)
5904{
5905 debug_printf_exec("execing '%s'\n", argv[0]);
5906 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5907 execvp(argv[0], argv);
5908 bb_perror_msg("can't execute '%s'", argv[0]);
5909 _exit(127); /* bash compat */
5910}
5911
5912#if ENABLE_HUSH_MODE_X
5913static void dump_cmd_in_x_mode(char **argv)
5914{
5915 if (G_x_mode && argv) {
5916 /* We want to output the line in one write op */
5917 char *buf, *p;
5918 int len;
5919 int n;
5920
5921 len = 3;
5922 n = 0;
5923 while (argv[n])
5924 len += strlen(argv[n++]) + 1;
5925 buf = xmalloc(len);
5926 buf[0] = '+';
5927 p = buf + 1;
5928 n = 0;
5929 while (argv[n])
5930 p += sprintf(p, " %s", argv[n++]);
5931 *p++ = '\n';
5932 *p = '\0';
5933 fputs(buf, stderr);
5934 free(buf);
5935 }
5936}
5937#else
5938# define dump_cmd_in_x_mode(argv) ((void)0)
5939#endif
5940
5941#if BB_MMU
5942#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5943 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5944#define pseudo_exec(nommu_save, command, argv_expanded) \
5945 pseudo_exec(command, argv_expanded)
5946#endif
5947
5948/* Called after [v]fork() in run_pipe, or from builtin_exec.
5949 * Never returns.
5950 * Don't exit() here. If you don't exec, use _exit instead.
5951 * The at_exit handlers apparently confuse the calling process,
5952 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5953static void pseudo_exec_argv(nommu_save_t *nommu_save,
5954 char **argv, int assignment_cnt,
5955 char **argv_expanded) NORETURN;
5956static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5957 char **argv, int assignment_cnt,
5958 char **argv_expanded)
5959{
5960 char **new_env;
5961
5962 new_env = expand_assignments(argv, assignment_cnt);
5963 dump_cmd_in_x_mode(new_env);
5964
5965 if (!argv[assignment_cnt]) {
5966 /* Case when we are here: ... | var=val | ...
5967 * (note that we do not exit early, i.e., do not optimize out
5968 * expand_assignments(): think about ... | var=`sleep 1` | ...
5969 */
5970 free_strings(new_env);
5971 _exit(EXIT_SUCCESS);
5972 }
5973
5974#if BB_MMU
5975 set_vars_and_save_old(new_env);
5976 free(new_env); /* optional */
5977 /* we can also destroy set_vars_and_save_old's return value,
5978 * to save memory */
5979#else
5980 nommu_save->new_env = new_env;
5981 nommu_save->old_vars = set_vars_and_save_old(new_env);
5982#endif
5983
5984 if (argv_expanded) {
5985 argv = argv_expanded;
5986 } else {
5987 argv = expand_strvec_to_strvec(argv + assignment_cnt);
5988#if !BB_MMU
5989 nommu_save->argv = argv;
5990#endif
5991 }
5992 dump_cmd_in_x_mode(argv);
5993
5994#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
5995 if (strchr(argv[0], '/') != NULL)
5996 goto skip;
5997#endif
5998
5999 /* Check if the command matches any of the builtins.
6000 * Depending on context, this might be redundant. But it's
6001 * easier to waste a few CPU cycles than it is to figure out
6002 * if this is one of those cases.
6003 */
6004 {
6005 /* On NOMMU, it is more expensive to re-execute shell
6006 * just in order to run echo or test builtin.
6007 * It's better to skip it here and run corresponding
6008 * non-builtin later. */
6009 const struct built_in_command *x;
6010 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6011 if (x) {
6012 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6013 }
6014 }
6015#if ENABLE_HUSH_FUNCTIONS
6016 /* Check if the command matches any functions */
6017 {
6018 const struct function *funcp = find_function(argv[0]);
6019 if (funcp) {
6020 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6021 }
6022 }
6023#endif
6024
6025#if ENABLE_FEATURE_SH_STANDALONE
6026 /* Check if the command matches any busybox applets */
6027 {
6028 int a = find_applet_by_name(argv[0]);
6029 if (a >= 0) {
6030# if BB_MMU /* see above why on NOMMU it is not allowed */
6031 if (APPLET_IS_NOEXEC(a)) {
6032 debug_printf_exec("running applet '%s'\n", argv[0]);
6033 run_applet_no_and_exit(a, argv);
6034 }
6035# endif
6036 /* Re-exec ourselves */
6037 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6038 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6039 execv(bb_busybox_exec_path, argv);
6040 /* If they called chroot or otherwise made the binary no longer
6041 * executable, fall through */
6042 }
6043 }
6044#endif
6045
6046#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6047 skip:
6048#endif
6049 execvp_or_die(argv);
6050}
6051
6052/* Called after [v]fork() in run_pipe
6053 */
6054static void pseudo_exec(nommu_save_t *nommu_save,
6055 struct command *command,
6056 char **argv_expanded) NORETURN;
6057static void pseudo_exec(nommu_save_t *nommu_save,
6058 struct command *command,
6059 char **argv_expanded)
6060{
6061 if (command->argv) {
6062 pseudo_exec_argv(nommu_save, command->argv,
6063 command->assignment_cnt, argv_expanded);
6064 }
6065
6066 if (command->group) {
6067 /* Cases when we are here:
6068 * ( list )
6069 * { list } &
6070 * ... | ( list ) | ...
6071 * ... | { list } | ...
6072 */
6073#if BB_MMU
6074 int rcode;
6075 debug_printf_exec("pseudo_exec: run_list\n");
6076 reset_traps_to_defaults();
6077 rcode = run_list(command->group);
6078 /* OK to leak memory by not calling free_pipe_list,
6079 * since this process is about to exit */
6080 _exit(rcode);
6081#else
6082 re_execute_shell(&nommu_save->argv_from_re_execing,
6083 command->group_as_string,
6084 G.global_argv[0],
6085 G.global_argv + 1,
6086 NULL);
6087#endif
6088 }
6089
6090 /* Case when we are here: ... | >file */
6091 debug_printf_exec("pseudo_exec'ed null command\n");
6092 _exit(EXIT_SUCCESS);
6093}
6094
6095#if ENABLE_HUSH_JOB
6096static const char *get_cmdtext(struct pipe *pi)
6097{
6098 char **argv;
6099 char *p;
6100 int len;
6101
6102 /* This is subtle. ->cmdtext is created only on first backgrounding.
6103 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6104 * On subsequent bg argv is trashed, but we won't use it */
6105 if (pi->cmdtext)
6106 return pi->cmdtext;
6107 argv = pi->cmds[0].argv;
6108 if (!argv || !argv[0]) {
6109 pi->cmdtext = xzalloc(1);
6110 return pi->cmdtext;
6111 }
6112
6113 len = 0;
6114 do {
6115 len += strlen(*argv) + 1;
6116 } while (*++argv);
6117 p = xmalloc(len);
6118 pi->cmdtext = p;
6119 argv = pi->cmds[0].argv;
6120 do {
6121 len = strlen(*argv);
6122 memcpy(p, *argv, len);
6123 p += len;
6124 *p++ = ' ';
6125 } while (*++argv);
6126 p[-1] = '\0';
6127 return pi->cmdtext;
6128}
6129
6130static void insert_bg_job(struct pipe *pi)
6131{
6132 struct pipe *job, **jobp;
6133 int i;
6134
6135 /* Linear search for the ID of the job to use */
6136 pi->jobid = 1;
6137 for (job = G.job_list; job; job = job->next)
6138 if (job->jobid >= pi->jobid)
6139 pi->jobid = job->jobid + 1;
6140
6141 /* Add job to the list of running jobs */
6142 jobp = &G.job_list;
6143 while ((job = *jobp) != NULL)
6144 jobp = &job->next;
6145 job = *jobp = xmalloc(sizeof(*job));
6146
6147 *job = *pi; /* physical copy */
6148 job->next = NULL;
6149 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6150 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6151 for (i = 0; i < pi->num_cmds; i++) {
6152 job->cmds[i].pid = pi->cmds[i].pid;
6153 /* all other fields are not used and stay zero */
6154 }
6155 job->cmdtext = xstrdup(get_cmdtext(pi));
6156
6157 if (G_interactive_fd)
6158 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6159 G.last_jobid = job->jobid;
6160}
6161
6162static void remove_bg_job(struct pipe *pi)
6163{
6164 struct pipe *prev_pipe;
6165
6166 if (pi == G.job_list) {
6167 G.job_list = pi->next;
6168 } else {
6169 prev_pipe = G.job_list;
6170 while (prev_pipe->next != pi)
6171 prev_pipe = prev_pipe->next;
6172 prev_pipe->next = pi->next;
6173 }
6174 if (G.job_list)
6175 G.last_jobid = G.job_list->jobid;
6176 else
6177 G.last_jobid = 0;
6178}
6179
6180/* Remove a backgrounded job */
6181static void delete_finished_bg_job(struct pipe *pi)
6182{
6183 remove_bg_job(pi);
6184 pi->stopped_cmds = 0;
6185 free_pipe(pi);
6186 free(pi);
6187}
6188#endif /* JOB */
6189
6190/* Check to see if any processes have exited -- if they
6191 * have, figure out why and see if a job has completed */
6192static int checkjobs(struct pipe* fg_pipe)
6193{
6194 int attributes;
6195 int status;
6196#if ENABLE_HUSH_JOB
6197 struct pipe *pi;
6198#endif
6199 pid_t childpid;
6200 int rcode = 0;
6201
6202 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6203
6204 attributes = WUNTRACED;
6205 if (fg_pipe == NULL)
6206 attributes |= WNOHANG;
6207
6208 errno = 0;
6209#if ENABLE_HUSH_FAST
6210 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6211//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6212//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6213 /* There was neither fork nor SIGCHLD since last waitpid */
6214 /* Avoid doing waitpid syscall if possible */
6215 if (!G.we_have_children) {
6216 errno = ECHILD;
6217 return -1;
6218 }
6219 if (fg_pipe == NULL) { /* is WNOHANG set? */
6220 /* We have children, but they did not exit
6221 * or stop yet (we saw no SIGCHLD) */
6222 return 0;
6223 }
6224 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6225 }
6226#endif
6227
6228/* Do we do this right?
6229 * bash-3.00# sleep 20 | false
6230 * <ctrl-Z pressed>
6231 * [3]+ Stopped sleep 20 | false
6232 * bash-3.00# echo $?
6233 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6234 * [hush 1.14.0: yes we do it right]
6235 */
6236 wait_more:
6237 while (1) {
6238 int i;
6239 int dead;
6240
6241#if ENABLE_HUSH_FAST
6242 i = G.count_SIGCHLD;
6243#endif
6244 childpid = waitpid(-1, &status, attributes);
6245 if (childpid <= 0) {
6246 if (childpid && errno != ECHILD)
6247 bb_perror_msg("waitpid");
6248#if ENABLE_HUSH_FAST
6249 else { /* Until next SIGCHLD, waitpid's are useless */
6250 G.we_have_children = (childpid == 0);
6251 G.handled_SIGCHLD = i;
6252//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6253 }
6254#endif
6255 break;
6256 }
6257 dead = WIFEXITED(status) || WIFSIGNALED(status);
6258
6259#if DEBUG_JOBS
6260 if (WIFSTOPPED(status))
6261 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6262 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6263 if (WIFSIGNALED(status))
6264 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6265 childpid, WTERMSIG(status), WEXITSTATUS(status));
6266 if (WIFEXITED(status))
6267 debug_printf_jobs("pid %d exited, exitcode %d\n",
6268 childpid, WEXITSTATUS(status));
6269#endif
6270 /* Were we asked to wait for fg pipe? */
6271 if (fg_pipe) {
6272 for (i = 0; i < fg_pipe->num_cmds; i++) {
6273 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6274 if (fg_pipe->cmds[i].pid != childpid)
6275 continue;
6276 if (dead) {
6277 fg_pipe->cmds[i].pid = 0;
6278 fg_pipe->alive_cmds--;
6279 if (i == fg_pipe->num_cmds - 1) {
6280 /* last process gives overall exitstatus */
6281 rcode = WEXITSTATUS(status);
6282 /* bash prints killer signal's name for *last*
6283 * process in pipe (prints just newline for SIGINT).
6284 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6285 */
6286 if (WIFSIGNALED(status)) {
6287 int sig = WTERMSIG(status);
6288 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6289 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6290 * Maybe we need to use sig | 128? */
6291 rcode = sig + 128;
6292 }
6293 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6294 }
6295 } else {
6296 fg_pipe->cmds[i].is_stopped = 1;
6297 fg_pipe->stopped_cmds++;
6298 }
6299 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6300 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6301 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6302 /* All processes in fg pipe have exited or stopped */
6303/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6304 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6305 * and "killall -STOP cat" */
6306 if (G_interactive_fd) {
6307#if ENABLE_HUSH_JOB
6308 if (fg_pipe->alive_cmds)
6309 insert_bg_job(fg_pipe);
6310#endif
6311 return rcode;
6312 }
6313 if (!fg_pipe->alive_cmds)
6314 return rcode;
6315 }
6316 /* There are still running processes in the fg pipe */
6317 goto wait_more; /* do waitpid again */
6318 }
6319 /* it wasnt fg_pipe, look for process in bg pipes */
6320 }
6321
6322#if ENABLE_HUSH_JOB
6323 /* We asked to wait for bg or orphaned children */
6324 /* No need to remember exitcode in this case */
6325 for (pi = G.job_list; pi; pi = pi->next) {
6326 for (i = 0; i < pi->num_cmds; i++) {
6327 if (pi->cmds[i].pid == childpid)
6328 goto found_pi_and_prognum;
6329 }
6330 }
6331 /* Happens when shell is used as init process (init=/bin/sh) */
6332 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6333 continue; /* do waitpid again */
6334
6335 found_pi_and_prognum:
6336 if (dead) {
6337 /* child exited */
6338 pi->cmds[i].pid = 0;
6339 pi->alive_cmds--;
6340 if (!pi->alive_cmds) {
6341 if (G_interactive_fd)
6342 printf(JOB_STATUS_FORMAT, pi->jobid,
6343 "Done", pi->cmdtext);
6344 delete_finished_bg_job(pi);
6345 }
6346 } else {
6347 /* child stopped */
6348 pi->cmds[i].is_stopped = 1;
6349 pi->stopped_cmds++;
6350 }
6351#endif
6352 } /* while (waitpid succeeds)... */
6353
6354 return rcode;
6355}
6356
6357#if ENABLE_HUSH_JOB
6358static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
6359{
6360 pid_t p;
6361 int rcode = checkjobs(fg_pipe);
6362 if (G_saved_tty_pgrp) {
6363 /* Job finished, move the shell to the foreground */
6364 p = getpgrp(); /* our process group id */
6365 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6366 tcsetpgrp(G_interactive_fd, p);
6367 }
6368 return rcode;
6369}
6370#endif
6371
6372/* Start all the jobs, but don't wait for anything to finish.
6373 * See checkjobs().
6374 *
6375 * Return code is normally -1, when the caller has to wait for children
6376 * to finish to determine the exit status of the pipe. If the pipe
6377 * is a simple builtin command, however, the action is done by the
6378 * time run_pipe returns, and the exit code is provided as the
6379 * return value.
6380 *
6381 * Returns -1 only if started some children. IOW: we have to
6382 * mask out retvals of builtins etc with 0xff!
6383 *
6384 * The only case when we do not need to [v]fork is when the pipe
6385 * is single, non-backgrounded, non-subshell command. Examples:
6386 * cmd ; ... { list } ; ...
6387 * cmd && ... { list } && ...
6388 * cmd || ... { list } || ...
6389 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6390 * or (if SH_STANDALONE) an applet, and we can run the { list }
6391 * with run_list. If it isn't one of these, we fork and exec cmd.
6392 *
6393 * Cases when we must fork:
6394 * non-single: cmd | cmd
6395 * backgrounded: cmd & { list } &
6396 * subshell: ( list ) [&]
6397 */
6398#if !ENABLE_HUSH_MODE_X
6399#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6400 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6401#endif
6402static int redirect_and_varexp_helper(char ***new_env_p,
6403 struct variable **old_vars_p,
6404 struct command *command,
6405 int squirrel[3],
6406 char **argv_expanded)
6407{
6408 /* setup_redirects acts on file descriptors, not FILEs.
6409 * This is perfect for work that comes after exec().
6410 * Is it really safe for inline use? Experimentally,
6411 * things seem to work. */
6412 int rcode = setup_redirects(command, squirrel);
6413 if (rcode == 0) {
6414 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6415 *new_env_p = new_env;
6416 dump_cmd_in_x_mode(new_env);
6417 dump_cmd_in_x_mode(argv_expanded);
6418 if (old_vars_p)
6419 *old_vars_p = set_vars_and_save_old(new_env);
6420 }
6421 return rcode;
6422}
6423static NOINLINE int run_pipe(struct pipe *pi)
6424{
6425 static const char *const null_ptr = NULL;
6426
6427 int cmd_no;
6428 int next_infd;
6429 struct command *command;
6430 char **argv_expanded;
6431 char **argv;
6432 /* it is not always needed, but we aim to smaller code */
6433 int squirrel[] = { -1, -1, -1 };
6434 int rcode;
6435
6436 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6437 debug_enter();
6438
6439 IF_HUSH_JOB(pi->pgrp = -1;)
6440 pi->stopped_cmds = 0;
6441 command = &pi->cmds[0];
6442 argv_expanded = NULL;
6443
6444 if (pi->num_cmds != 1
6445 || pi->followup == PIPE_BG
6446 || command->cmd_type == CMD_SUBSHELL
6447 ) {
6448 goto must_fork;
6449 }
6450
6451 pi->alive_cmds = 1;
6452
6453 debug_printf_exec(": group:%p argv:'%s'\n",
6454 command->group, command->argv ? command->argv[0] : "NONE");
6455
6456 if (command->group) {
6457#if ENABLE_HUSH_FUNCTIONS
6458 if (command->cmd_type == CMD_FUNCDEF) {
6459 /* "executing" func () { list } */
6460 struct function *funcp;
6461
6462 funcp = new_function(command->argv[0]);
6463 /* funcp->name is already set to argv[0] */
6464 funcp->body = command->group;
6465# if !BB_MMU
6466 funcp->body_as_string = command->group_as_string;
6467 command->group_as_string = NULL;
6468# endif
6469 command->group = NULL;
6470 command->argv[0] = NULL;
6471 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6472 funcp->parent_cmd = command;
6473 command->child_func = funcp;
6474
6475 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6476 debug_leave();
6477 return EXIT_SUCCESS;
6478 }
6479#endif
6480 /* { list } */
6481 debug_printf("non-subshell group\n");
6482 rcode = 1; /* exitcode if redir failed */
6483 if (setup_redirects(command, squirrel) == 0) {
6484 debug_printf_exec(": run_list\n");
6485 rcode = run_list(command->group) & 0xff;
6486 }
6487 restore_redirects(squirrel);
6488 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6489 debug_leave();
6490 debug_printf_exec("run_pipe: return %d\n", rcode);
6491 return rcode;
6492 }
6493
6494 argv = command->argv ? command->argv : (char **) &null_ptr;
6495 {
6496 const struct built_in_command *x;
6497#if ENABLE_HUSH_FUNCTIONS
6498 const struct function *funcp;
6499#else
6500 enum { funcp = 0 };
6501#endif
6502 char **new_env = NULL;
6503 struct variable *old_vars = NULL;
6504
6505 if (argv[command->assignment_cnt] == NULL) {
6506 /* Assignments, but no command */
6507 /* Ensure redirects take effect (that is, create files).
6508 * Try "a=t >file" */
6509#if 0 /* A few cases in testsuite fail with this code. FIXME */
6510 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6511 /* Set shell variables */
6512 if (new_env) {
6513 argv = new_env;
6514 while (*argv) {
6515 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6516 /* Do we need to flag set_local_var() errors?
6517 * "assignment to readonly var" and "putenv error"
6518 */
6519 argv++;
6520 }
6521 }
6522 /* Redirect error sets $? to 1. Otherwise,
6523 * if evaluating assignment value set $?, retain it.
6524 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6525 if (rcode == 0)
6526 rcode = G.last_exitcode;
6527 /* Exit, _skipping_ variable restoring code: */
6528 goto clean_up_and_ret0;
6529
6530#else /* Older, bigger, but more correct code */
6531
6532 rcode = setup_redirects(command, squirrel);
6533 restore_redirects(squirrel);
6534 /* Set shell variables */
6535 if (G_x_mode)
6536 bb_putchar_stderr('+');
6537 while (*argv) {
6538 char *p = expand_string_to_string(*argv);
6539 if (G_x_mode)
6540 fprintf(stderr, " %s", p);
6541 debug_printf_exec("set shell var:'%s'->'%s'\n",
6542 *argv, p);
6543 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6544 /* Do we need to flag set_local_var() errors?
6545 * "assignment to readonly var" and "putenv error"
6546 */
6547 argv++;
6548 }
6549 if (G_x_mode)
6550 bb_putchar_stderr('\n');
6551 /* Redirect error sets $? to 1. Otherwise,
6552 * if evaluating assignment value set $?, retain it.
6553 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6554 if (rcode == 0)
6555 rcode = G.last_exitcode;
6556 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6557 debug_leave();
6558 debug_printf_exec("run_pipe: return %d\n", rcode);
6559 return rcode;
6560#endif
6561 }
6562
6563 /* Expand the rest into (possibly) many strings each */
6564 if (0) {}
6565#if ENABLE_HUSH_BASH_COMPAT
6566 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6567 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6568 }
6569#endif
6570#ifdef CMD_SINGLEWORD_NOGLOB_COND
6571 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
6572 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
6573 }
6574#endif
6575 else {
6576 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6577 }
6578
6579 /* if someone gives us an empty string: `cmd with empty output` */
6580 if (!argv_expanded[0]) {
6581 free(argv_expanded);
6582 debug_leave();
6583 return G.last_exitcode;
6584 }
6585
6586 x = find_builtin(argv_expanded[0]);
6587#if ENABLE_HUSH_FUNCTIONS
6588 funcp = NULL;
6589 if (!x)
6590 funcp = find_function(argv_expanded[0]);
6591#endif
6592 if (x || funcp) {
6593 if (!funcp) {
6594 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6595 debug_printf("exec with redirects only\n");
6596 rcode = setup_redirects(command, NULL);
6597 goto clean_up_and_ret1;
6598 }
6599 }
6600 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6601 if (rcode == 0) {
6602 if (!funcp) {
6603 debug_printf_exec(": builtin '%s' '%s'...\n",
6604 x->b_cmd, argv_expanded[1]);
6605 rcode = x->b_function(argv_expanded) & 0xff;
6606 fflush_all();
6607 }
6608#if ENABLE_HUSH_FUNCTIONS
6609 else {
6610# if ENABLE_HUSH_LOCAL
6611 struct variable **sv;
6612 sv = G.shadowed_vars_pp;
6613 G.shadowed_vars_pp = &old_vars;
6614# endif
6615 debug_printf_exec(": function '%s' '%s'...\n",
6616 funcp->name, argv_expanded[1]);
6617 rcode = run_function(funcp, argv_expanded) & 0xff;
6618# if ENABLE_HUSH_LOCAL
6619 G.shadowed_vars_pp = sv;
6620# endif
6621 }
6622#endif
6623 }
6624 clean_up_and_ret:
6625 unset_vars(new_env);
6626 add_vars(old_vars);
6627/* clean_up_and_ret0: */
6628 restore_redirects(squirrel);
6629 clean_up_and_ret1:
6630 free(argv_expanded);
6631 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6632 debug_leave();
6633 debug_printf_exec("run_pipe return %d\n", rcode);
6634 return rcode;
6635 }
6636
6637 if (ENABLE_FEATURE_SH_STANDALONE) {
6638 int n = find_applet_by_name(argv_expanded[0]);
6639 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6640 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6641 if (rcode == 0) {
6642 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6643 argv_expanded[0], argv_expanded[1]);
6644 rcode = run_nofork_applet(n, argv_expanded);
6645 }
6646 goto clean_up_and_ret;
6647 }
6648 }
6649 /* It is neither builtin nor applet. We must fork. */
6650 }
6651
6652 must_fork:
6653 /* NB: argv_expanded may already be created, and that
6654 * might include `cmd` runs! Do not rerun it! We *must*
6655 * use argv_expanded if it's non-NULL */
6656
6657 /* Going to fork a child per each pipe member */
6658 pi->alive_cmds = 0;
6659 next_infd = 0;
6660
6661 cmd_no = 0;
6662 while (cmd_no < pi->num_cmds) {
6663 struct fd_pair pipefds;
6664#if !BB_MMU
6665 volatile nommu_save_t nommu_save;
6666 nommu_save.new_env = NULL;
6667 nommu_save.old_vars = NULL;
6668 nommu_save.argv = NULL;
6669 nommu_save.argv_from_re_execing = NULL;
6670#endif
6671 command = &pi->cmds[cmd_no];
6672 cmd_no++;
6673 if (command->argv) {
6674 debug_printf_exec(": pipe member '%s' '%s'...\n",
6675 command->argv[0], command->argv[1]);
6676 } else {
6677 debug_printf_exec(": pipe member with no argv\n");
6678 }
6679
6680 /* pipes are inserted between pairs of commands */
6681 pipefds.rd = 0;
6682 pipefds.wr = 1;
6683 if (cmd_no < pi->num_cmds)
6684 xpiped_pair(pipefds);
6685
6686 command->pid = BB_MMU ? fork() : vfork();
6687 if (!command->pid) { /* child */
6688#if ENABLE_HUSH_JOB
6689 disable_restore_tty_pgrp_on_exit();
6690 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6691
6692 /* Every child adds itself to new process group
6693 * with pgid == pid_of_first_child_in_pipe */
6694 if (G.run_list_level == 1 && G_interactive_fd) {
6695 pid_t pgrp;
6696 pgrp = pi->pgrp;
6697 if (pgrp < 0) /* true for 1st process only */
6698 pgrp = getpid();
6699 if (setpgid(0, pgrp) == 0
6700 && pi->followup != PIPE_BG
6701 && G_saved_tty_pgrp /* we have ctty */
6702 ) {
6703 /* We do it in *every* child, not just first,
6704 * to avoid races */
6705 tcsetpgrp(G_interactive_fd, pgrp);
6706 }
6707 }
6708#endif
6709 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6710 /* 1st cmd in backgrounded pipe
6711 * should have its stdin /dev/null'ed */
6712 close(0);
6713 if (open(bb_dev_null, O_RDONLY))
6714 xopen("/", O_RDONLY);
6715 } else {
6716 xmove_fd(next_infd, 0);
6717 }
6718 xmove_fd(pipefds.wr, 1);
6719 if (pipefds.rd > 1)
6720 close(pipefds.rd);
6721 /* Like bash, explicit redirects override pipes,
6722 * and the pipe fd is available for dup'ing. */
6723 if (setup_redirects(command, NULL))
6724 _exit(1);
6725
6726 /* Restore default handlers just prior to exec */
6727 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6728
6729 /* Stores to nommu_save list of env vars putenv'ed
6730 * (NOMMU, on MMU we don't need that) */
6731 /* cast away volatility... */
6732 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6733 /* pseudo_exec() does not return */
6734 }
6735
6736 /* parent or error */
6737#if ENABLE_HUSH_FAST
6738 G.count_SIGCHLD++;
6739//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6740#endif
6741 enable_restore_tty_pgrp_on_exit();
6742#if !BB_MMU
6743 /* Clean up after vforked child */
6744 free(nommu_save.argv);
6745 free(nommu_save.argv_from_re_execing);
6746 unset_vars(nommu_save.new_env);
6747 add_vars(nommu_save.old_vars);
6748#endif
6749 free(argv_expanded);
6750 argv_expanded = NULL;
6751 if (command->pid < 0) { /* [v]fork failed */
6752 /* Clearly indicate, was it fork or vfork */
6753 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6754 } else {
6755 pi->alive_cmds++;
6756#if ENABLE_HUSH_JOB
6757 /* Second and next children need to know pid of first one */
6758 if (pi->pgrp < 0)
6759 pi->pgrp = command->pid;
6760#endif
6761 }
6762
6763 if (cmd_no > 1)
6764 close(next_infd);
6765 if (cmd_no < pi->num_cmds)
6766 close(pipefds.wr);
6767 /* Pass read (output) pipe end to next iteration */
6768 next_infd = pipefds.rd;
6769 }
6770
6771 if (!pi->alive_cmds) {
6772 debug_leave();
6773 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6774 return 1;
6775 }
6776
6777 debug_leave();
6778 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6779 return -1;
6780}
6781
6782#ifndef debug_print_tree
6783static void debug_print_tree(struct pipe *pi, int lvl)
6784{
6785 static const char *const PIPE[] = {
6786 [PIPE_SEQ] = "SEQ",
6787 [PIPE_AND] = "AND",
6788 [PIPE_OR ] = "OR" ,
6789 [PIPE_BG ] = "BG" ,
6790 };
6791 static const char *RES[] = {
6792 [RES_NONE ] = "NONE" ,
6793# if ENABLE_HUSH_IF
6794 [RES_IF ] = "IF" ,
6795 [RES_THEN ] = "THEN" ,
6796 [RES_ELIF ] = "ELIF" ,
6797 [RES_ELSE ] = "ELSE" ,
6798 [RES_FI ] = "FI" ,
6799# endif
6800# if ENABLE_HUSH_LOOPS
6801 [RES_FOR ] = "FOR" ,
6802 [RES_WHILE] = "WHILE",
6803 [RES_UNTIL] = "UNTIL",
6804 [RES_DO ] = "DO" ,
6805 [RES_DONE ] = "DONE" ,
6806# endif
6807# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6808 [RES_IN ] = "IN" ,
6809# endif
6810# if ENABLE_HUSH_CASE
6811 [RES_CASE ] = "CASE" ,
6812 [RES_CASE_IN ] = "CASE_IN" ,
6813 [RES_MATCH] = "MATCH",
6814 [RES_CASE_BODY] = "CASE_BODY",
6815 [RES_ESAC ] = "ESAC" ,
6816# endif
6817 [RES_XXXX ] = "XXXX" ,
6818 [RES_SNTX ] = "SNTX" ,
6819 };
6820 static const char *const CMDTYPE[] = {
6821 "{}",
6822 "()",
6823 "[noglob]",
6824# if ENABLE_HUSH_FUNCTIONS
6825 "func()",
6826# endif
6827 };
6828
6829 int pin, prn;
6830
6831 pin = 0;
6832 while (pi) {
6833 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6834 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6835 prn = 0;
6836 while (prn < pi->num_cmds) {
6837 struct command *command = &pi->cmds[prn];
6838 char **argv = command->argv;
6839
6840 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6841 lvl*2, "", prn,
6842 command->assignment_cnt);
6843 if (command->group) {
6844 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6845 CMDTYPE[command->cmd_type],
6846 argv
6847# if !BB_MMU
6848 , " group_as_string:", command->group_as_string
6849# else
6850 , "", ""
6851# endif
6852 );
6853 debug_print_tree(command->group, lvl+1);
6854 prn++;
6855 continue;
6856 }
6857 if (argv) while (*argv) {
6858 fprintf(stderr, " '%s'", *argv);
6859 argv++;
6860 }
6861 fprintf(stderr, "\n");
6862 prn++;
6863 }
6864 pi = pi->next;
6865 pin++;
6866 }
6867}
6868#endif /* debug_print_tree */
6869
6870/* NB: called by pseudo_exec, and therefore must not modify any
6871 * global data until exec/_exit (we can be a child after vfork!) */
6872static int run_list(struct pipe *pi)
6873{
6874#if ENABLE_HUSH_CASE
6875 char *case_word = NULL;
6876#endif
6877#if ENABLE_HUSH_LOOPS
6878 struct pipe *loop_top = NULL;
6879 char **for_lcur = NULL;
6880 char **for_list = NULL;
6881#endif
6882 smallint last_followup;
6883 smalluint rcode;
6884#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6885 smalluint cond_code = 0;
6886#else
6887 enum { cond_code = 0 };
6888#endif
6889#if HAS_KEYWORDS
6890 smallint rword; /* enum reserved_style */
6891 smallint last_rword; /* ditto */
6892#endif
6893
6894 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6895 debug_enter();
6896
6897#if ENABLE_HUSH_LOOPS
6898 /* Check syntax for "for" */
6899 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6900 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6901 continue;
6902 /* current word is FOR or IN (BOLD in comments below) */
6903 if (cpipe->next == NULL) {
6904 syntax_error("malformed for");
6905 debug_leave();
6906 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6907 return 1;
6908 }
6909 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6910 if (cpipe->next->res_word == RES_DO)
6911 continue;
6912 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6913 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6914 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6915 ) {
6916 syntax_error("malformed for");
6917 debug_leave();
6918 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6919 return 1;
6920 }
6921 }
6922#endif
6923
6924 /* Past this point, all code paths should jump to ret: label
6925 * in order to return, no direct "return" statements please.
6926 * This helps to ensure that no memory is leaked. */
6927
6928#if ENABLE_HUSH_JOB
6929 G.run_list_level++;
6930#endif
6931
6932#if HAS_KEYWORDS
6933 rword = RES_NONE;
6934 last_rword = RES_XXXX;
6935#endif
6936 last_followup = PIPE_SEQ;
6937 rcode = G.last_exitcode;
6938
6939 /* Go through list of pipes, (maybe) executing them. */
6940 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6941 if (G.flag_SIGINT)
6942 break;
6943
6944 IF_HAS_KEYWORDS(rword = pi->res_word;)
6945 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6946 rword, cond_code, last_rword);
6947#if ENABLE_HUSH_LOOPS
6948 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6949 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6950 ) {
6951 /* start of a loop: remember where loop starts */
6952 loop_top = pi;
6953 G.depth_of_loop++;
6954 }
6955#endif
6956 /* Still in the same "if...", "then..." or "do..." branch? */
6957 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6958 if ((rcode == 0 && last_followup == PIPE_OR)
6959 || (rcode != 0 && last_followup == PIPE_AND)
6960 ) {
6961 /* It is "<true> || CMD" or "<false> && CMD"
6962 * and we should not execute CMD */
6963 debug_printf_exec("skipped cmd because of || or &&\n");
6964 last_followup = pi->followup;
6965 continue;
6966 }
6967 }
6968 last_followup = pi->followup;
6969 IF_HAS_KEYWORDS(last_rword = rword;)
6970#if ENABLE_HUSH_IF
6971 if (cond_code) {
6972 if (rword == RES_THEN) {
6973 /* if false; then ... fi has exitcode 0! */
6974 G.last_exitcode = rcode = EXIT_SUCCESS;
6975 /* "if <false> THEN cmd": skip cmd */
6976 continue;
6977 }
6978 } else {
6979 if (rword == RES_ELSE || rword == RES_ELIF) {
6980 /* "if <true> then ... ELSE/ELIF cmd":
6981 * skip cmd and all following ones */
6982 break;
6983 }
6984 }
6985#endif
6986#if ENABLE_HUSH_LOOPS
6987 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
6988 if (!for_lcur) {
6989 /* first loop through for */
6990
6991 static const char encoded_dollar_at[] ALIGN1 = {
6992 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
6993 }; /* encoded representation of "$@" */
6994 static const char *const encoded_dollar_at_argv[] = {
6995 encoded_dollar_at, NULL
6996 }; /* argv list with one element: "$@" */
6997 char **vals;
6998
6999 vals = (char**)encoded_dollar_at_argv;
7000 if (pi->next->res_word == RES_IN) {
7001 /* if no variable values after "in" we skip "for" */
7002 if (!pi->next->cmds[0].argv) {
7003 G.last_exitcode = rcode = EXIT_SUCCESS;
7004 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7005 break;
7006 }
7007 vals = pi->next->cmds[0].argv;
7008 } /* else: "for var; do..." -> assume "$@" list */
7009 /* create list of variable values */
7010 debug_print_strings("for_list made from", vals);
7011 for_list = expand_strvec_to_strvec(vals);
7012 for_lcur = for_list;
7013 debug_print_strings("for_list", for_list);
7014 }
7015 if (!*for_lcur) {
7016 /* "for" loop is over, clean up */
7017 free(for_list);
7018 for_list = NULL;
7019 for_lcur = NULL;
7020 break;
7021 }
7022 /* Insert next value from for_lcur */
7023 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7024 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7025 continue;
7026 }
7027 if (rword == RES_IN) {
7028 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7029 }
7030 if (rword == RES_DONE) {
7031 continue; /* "done" has no cmds too */
7032 }
7033#endif
7034#if ENABLE_HUSH_CASE
7035 if (rword == RES_CASE) {
7036 case_word = expand_strvec_to_string(pi->cmds->argv);
7037 continue;
7038 }
7039 if (rword == RES_MATCH) {
7040 char **argv;
7041
7042 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7043 break;
7044 /* all prev words didn't match, does this one match? */
7045 argv = pi->cmds->argv;
7046 while (*argv) {
7047 char *pattern = expand_string_to_string(*argv);
7048 /* TODO: which FNM_xxx flags to use? */
7049 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7050 free(pattern);
7051 if (cond_code == 0) { /* match! we will execute this branch */
7052 free(case_word); /* make future "word)" stop */
7053 case_word = NULL;
7054 break;
7055 }
7056 argv++;
7057 }
7058 continue;
7059 }
7060 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7061 if (cond_code != 0)
7062 continue; /* not matched yet, skip this pipe */
7063 }
7064#endif
7065 /* Just pressing <enter> in shell should check for jobs.
7066 * OTOH, in non-interactive shell this is useless
7067 * and only leads to extra job checks */
7068 if (pi->num_cmds == 0) {
7069 if (G_interactive_fd)
7070 goto check_jobs_and_continue;
7071 continue;
7072 }
7073
7074 /* After analyzing all keywords and conditions, we decided
7075 * to execute this pipe. NB: have to do checkjobs(NULL)
7076 * after run_pipe to collect any background children,
7077 * even if list execution is to be stopped. */
7078 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7079 {
7080 int r;
7081#if ENABLE_HUSH_LOOPS
7082 G.flag_break_continue = 0;
7083#endif
7084 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7085 if (r != -1) {
7086 /* We ran a builtin, function, or group.
7087 * rcode is already known
7088 * and we don't need to wait for anything. */
7089 G.last_exitcode = rcode;
7090 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7091 check_and_run_traps(0);
7092#if ENABLE_HUSH_LOOPS
7093 /* Was it "break" or "continue"? */
7094 if (G.flag_break_continue) {
7095 smallint fbc = G.flag_break_continue;
7096 /* We might fall into outer *loop*,
7097 * don't want to break it too */
7098 if (loop_top) {
7099 G.depth_break_continue--;
7100 if (G.depth_break_continue == 0)
7101 G.flag_break_continue = 0;
7102 /* else: e.g. "continue 2" should *break* once, *then* continue */
7103 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7104 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7105 goto check_jobs_and_break;
7106 /* "continue": simulate end of loop */
7107 rword = RES_DONE;
7108 continue;
7109 }
7110#endif
7111#if ENABLE_HUSH_FUNCTIONS
7112 if (G.flag_return_in_progress == 1) {
7113 /* same as "goto check_jobs_and_break" */
7114 checkjobs(NULL);
7115 break;
7116 }
7117#endif
7118 } else if (pi->followup == PIPE_BG) {
7119 /* What does bash do with attempts to background builtins? */
7120 /* even bash 3.2 doesn't do that well with nested bg:
7121 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7122 * I'm NOT treating inner &'s as jobs */
7123 check_and_run_traps(0);
7124#if ENABLE_HUSH_JOB
7125 if (G.run_list_level == 1)
7126 insert_bg_job(pi);
7127#endif
7128 /* Last command's pid goes to $! */
7129 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7130 G.last_exitcode = rcode = EXIT_SUCCESS;
7131 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7132 } else {
7133#if ENABLE_HUSH_JOB
7134 if (G.run_list_level == 1 && G_interactive_fd) {
7135 /* Waits for completion, then fg's main shell */
7136 rcode = checkjobs_and_fg_shell(pi);
7137 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7138 check_and_run_traps(0);
7139 } else
7140#endif
7141 { /* This one just waits for completion */
7142 rcode = checkjobs(pi);
7143 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7144 check_and_run_traps(0);
7145 }
7146 G.last_exitcode = rcode;
7147 }
7148 }
7149
7150 /* Analyze how result affects subsequent commands */
7151#if ENABLE_HUSH_IF
7152 if (rword == RES_IF || rword == RES_ELIF)
7153 cond_code = rcode;
7154#endif
7155#if ENABLE_HUSH_LOOPS
7156 /* Beware of "while false; true; do ..."! */
7157 if (pi->next && pi->next->res_word == RES_DO) {
7158 if (rword == RES_WHILE) {
7159 if (rcode) {
7160 /* "while false; do...done" - exitcode 0 */
7161 G.last_exitcode = rcode = EXIT_SUCCESS;
7162 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7163 goto check_jobs_and_break;
7164 }
7165 }
7166 if (rword == RES_UNTIL) {
7167 if (!rcode) {
7168 debug_printf_exec(": until expr is true: breaking\n");
7169 check_jobs_and_break:
7170 checkjobs(NULL);
7171 break;
7172 }
7173 }
7174 }
7175#endif
7176
7177 check_jobs_and_continue:
7178 checkjobs(NULL);
7179 } /* for (pi) */
7180
7181#if ENABLE_HUSH_JOB
7182 G.run_list_level--;
7183#endif
7184#if ENABLE_HUSH_LOOPS
7185 if (loop_top)
7186 G.depth_of_loop--;
7187 free(for_list);
7188#endif
7189#if ENABLE_HUSH_CASE
7190 free(case_word);
7191#endif
7192 debug_leave();
7193 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7194 return rcode;
7195}
7196
7197/* Select which version we will use */
7198static int run_and_free_list(struct pipe *pi)
7199{
7200 int rcode = 0;
7201 debug_printf_exec("run_and_free_list entered\n");
7202 if (!G.n_mode) {
7203 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7204 rcode = run_list(pi);
7205 }
7206 /* free_pipe_list has the side effect of clearing memory.
7207 * In the long run that function can be merged with run_list,
7208 * but doing that now would hobble the debugging effort. */
7209 free_pipe_list(pi);
7210 debug_printf_exec("run_and_free_list return %d\n", rcode);
7211 return rcode;
7212}
7213
7214
Denis Vlasenkof9375282009-04-05 19:13:39 +00007215/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007216static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007217{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007218 unsigned sig;
7219 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007220 sigset_t old_blocked_set;
7221
7222 if (!G.inherited_set_is_saved) {
7223 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7224 G.inherited_set = G.blocked_set;
7225 }
7226 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007227
Denis Vlasenkof9375282009-04-05 19:13:39 +00007228 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007229 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007230 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007231 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007232 mask |= SPECIAL_JOB_SIGS;
7233 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007234 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007235
Denis Vlasenkof9375282009-04-05 19:13:39 +00007236 sig = 0;
7237 while (mask) {
7238 if (mask & 1)
7239 sigaddset(&G.blocked_set, sig);
7240 mask >>= 1;
7241 sig++;
7242 }
7243 sigdelset(&G.blocked_set, SIGCHLD);
7244
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007245 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7246 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7247
Denis Vlasenkof9375282009-04-05 19:13:39 +00007248 /* POSIX allows shell to re-enable SIGCHLD
7249 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007250#if ENABLE_HUSH_FAST
7251 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007252 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007253 signal(SIGCHLD, SIGCHLD_handler);
7254#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007255 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007256 signal(SIGCHLD, SIG_DFL);
7257#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007258
7259 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007260}
7261
7262#if ENABLE_HUSH_JOB
7263/* helper */
7264static void maybe_set_to_sigexit(int sig)
7265{
7266 void (*handler)(int);
7267 /* non_DFL_mask'ed signals are, well, masked,
7268 * no need to set handler for them.
7269 */
7270 if (!((G.non_DFL_mask >> sig) & 1)) {
7271 handler = signal(sig, sigexit);
7272 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7273 signal(sig, handler);
7274 }
7275}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007276/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007277static void set_fatal_handlers(void)
7278{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007279 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007280 if (HUSH_DEBUG) {
7281 maybe_set_to_sigexit(SIGILL );
7282 maybe_set_to_sigexit(SIGFPE );
7283 maybe_set_to_sigexit(SIGBUS );
7284 maybe_set_to_sigexit(SIGSEGV);
7285 maybe_set_to_sigexit(SIGTRAP);
7286 } /* else: hush is perfect. what SEGV? */
7287 maybe_set_to_sigexit(SIGABRT);
7288 /* bash 3.2 seems to handle these just like 'fatal' ones */
7289 maybe_set_to_sigexit(SIGPIPE);
7290 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007291 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007292 * if we aren't interactive... but in this case
7293 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007294 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007295 /*maybe_set_to_sigexit(SIGTERM);*/
7296 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007297}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007298#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007299
Denis Vlasenkod5762932009-03-31 11:22:57 +00007300static int set_mode(const char cstate, const char mode)
7301{
7302 int state = (cstate == '-' ? 1 : 0);
7303 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007304 case 'n': G.n_mode = state; break;
7305 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007306 default: return EXIT_FAILURE;
7307 }
7308 return EXIT_SUCCESS;
7309}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007310
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007311int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007312int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007313{
7314 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007315 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007316 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007317 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00007318
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007319 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007320 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007321 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007322#if !BB_MMU
7323 G.argv0_for_re_execing = argv[0];
7324#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007325 /* Deal with HUSH_VERSION */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007326 G.shell_ver.flg_export = 1;
7327 G.shell_ver.flg_read_only = 1;
7328 /* Code which handles ${var/P/R} needs writable values for all variables,
7329 * therefore we xstrdup: */
7330 G.shell_ver.varstr = xstrdup(hush_version_str),
Denis Vlasenko87a86552008-07-29 19:43:10 +00007331 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007332 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007333 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007334 /* reinstate HUSH_VERSION in environment */
7335 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7336 putenv(G.shell_ver.varstr);
7337
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007338 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007339 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007340 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007341 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007342 if (e) while (*e) {
7343 char *value = strchr(*e, '=');
7344 if (value) { /* paranoia */
7345 cur_var->next = xzalloc(sizeof(*cur_var));
7346 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007347 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007348 cur_var->max_len = strlen(*e);
7349 cur_var->flg_export = 1;
7350 }
7351 e++;
7352 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007353
7354 /* Export PWD */
7355 set_pwd_var(/*exp:*/ 1);
7356 /* bash also exports SHLVL and _,
7357 * and sets (but doesn't export) the following variables:
7358 * BASH=/bin/bash
7359 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7360 * BASH_VERSION='3.2.0(1)-release'
7361 * HOSTTYPE=i386
7362 * MACHTYPE=i386-pc-linux-gnu
7363 * OSTYPE=linux-gnu
7364 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007365 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007366 * EUID=<NNNNN>
7367 * UID=<NNNNN>
7368 * GROUPS=()
7369 * LINES=<NNN>
7370 * COLUMNS=<NNN>
7371 * BASH_ARGC=()
7372 * BASH_ARGV=()
7373 * BASH_LINENO=()
7374 * BASH_SOURCE=()
7375 * DIRSTACK=()
7376 * PIPESTATUS=([0]="0")
7377 * HISTFILE=/<xxx>/.bash_history
7378 * HISTFILESIZE=500
7379 * HISTSIZE=500
7380 * MAILCHECK=60
7381 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7382 * SHELL=/bin/bash
7383 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7384 * TERM=dumb
7385 * OPTERR=1
7386 * OPTIND=1
7387 * IFS=$' \t\n'
7388 * PS1='\s-\v\$ '
7389 * PS2='> '
7390 * PS4='+ '
7391 */
7392
Denis Vlasenko38f63192007-01-22 09:03:07 +00007393#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007394 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007395#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007396 G.global_argc = argc;
7397 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007398 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007399 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007400
Denis Vlasenkoed782372009-04-10 00:45:02 +00007401 if (setjmp(die_jmp)) {
7402 /* xfunc has failed! die die die */
7403 /* no EXIT traps, this is an escape hatch! */
7404 G.exiting = 1;
7405 hush_exit(xfunc_error_retval);
7406 }
7407
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007408 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007409 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007410 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007411 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007412 * in order to intercept (more) signals.
7413 */
7414
7415 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007416 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007417 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007418 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007419 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007420#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007421 "<:$:R:V:"
7422# if ENABLE_HUSH_FUNCTIONS
7423 "F:"
7424# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007425#endif
7426 );
7427 if (opt <= 0)
7428 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007429 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007430 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007431 /* Possibilities:
7432 * sh ... -c 'script'
7433 * sh ... -c 'script' ARG0 [ARG1...]
7434 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007435 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007436 * "" needs to be replaced with NULL
7437 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007438 * Note: the form without ARG0 never happens:
7439 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007440 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007441 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007442 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007443 G.root_ppid = getppid();
7444 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007445 G.global_argv = argv + optind;
7446 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007447 if (builtin_argc) {
7448 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7449 const struct built_in_command *x;
7450
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007451 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007452 x = find_builtin(optarg);
7453 if (x) { /* paranoia */
7454 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7455 G.global_argv += builtin_argc;
7456 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007457 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007458 }
7459 goto final_return;
7460 }
7461 if (!G.global_argv[0]) {
7462 /* -c 'script' (no params): prevent empty $0 */
7463 G.global_argv--; /* points to argv[i] of 'script' */
7464 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007465 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007466 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007467 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007468 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007469 goto final_return;
7470 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007471 /* Well, we cannot just declare interactiveness,
7472 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007473 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007474 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007475 case 's':
7476 /* "-s" means "read from stdin", but this is how we always
7477 * operate, so simply do nothing here. */
7478 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007479#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007480 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007481 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007482 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007483 case '$': {
7484 unsigned long long empty_trap_mask;
7485
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007486 G.root_pid = bb_strtou(optarg, &optarg, 16);
7487 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007488 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7489 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007490 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7491 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007492 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007493 optarg++;
7494 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007495 optarg++;
7496 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7497 if (empty_trap_mask != 0) {
7498 int sig;
7499 init_sigmasks();
7500 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7501 for (sig = 1; sig < NSIG; sig++) {
7502 if (empty_trap_mask & (1LL << sig)) {
7503 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7504 sigaddset(&G.blocked_set, sig);
7505 }
7506 }
7507 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7508 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007509# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007510 optarg++;
7511 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007512# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007513 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007514 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007515 case 'R':
7516 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007517 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007518 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007519# if ENABLE_HUSH_FUNCTIONS
7520 case 'F': {
7521 struct function *funcp = new_function(optarg);
7522 /* funcp->name is already set to optarg */
7523 /* funcp->body is set to NULL. It's a special case. */
7524 funcp->body_as_string = argv[optind];
7525 optind++;
7526 break;
7527 }
7528# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007529#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007530 case 'n':
7531 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007532 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007533 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007534 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007535#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007536 fprintf(stderr, "Usage: sh [FILE]...\n"
7537 " or: sh -c command [args]...\n\n");
7538 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007539#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007540 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007541#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007542 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007543 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007544
Denys Vlasenkodea47882009-10-09 15:40:49 +02007545 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007546 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007547 G.root_ppid = getppid();
7548 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007549
7550 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007551 if (argv[0] && argv[0][0] == '-') {
7552 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007553 debug_printf("sourcing /etc/profile\n");
7554 input = fopen_for_read("/etc/profile");
7555 if (input != NULL) {
7556 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007557 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007558 parse_and_run_file(input);
7559 fclose(input);
7560 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007561 /* bash: after sourcing /etc/profile,
7562 * tries to source (in the given order):
7563 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007564 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007565 * bash also sources ~/.bash_logout on exit.
7566 * If called as sh, skips .bash_XXX files.
7567 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007568 }
7569
Denis Vlasenkof9375282009-04-05 19:13:39 +00007570 if (argv[optind]) {
7571 FILE *input;
7572 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007573 * "bash <script>" (which is never interactive (unless -i?))
7574 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007575 * If called as sh, does the same but with $ENV.
7576 */
7577 debug_printf("running script '%s'\n", argv[optind]);
7578 G.global_argv = argv + optind;
7579 G.global_argc = argc - optind;
7580 input = xfopen_for_read(argv[optind]);
7581 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007582 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007583 parse_and_run_file(input);
7584#if ENABLE_FEATURE_CLEAN_UP
7585 fclose(input);
7586#endif
7587 goto final_return;
7588 }
7589
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007590 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007591 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007592 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007593
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007594 /* A shell is interactive if the '-i' flag was given,
7595 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007596 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007597 * no arguments remaining or the -s flag given
7598 * standard input is a terminal
7599 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007600 * Refer to Posix.2, the description of the 'sh' utility.
7601 */
7602#if ENABLE_HUSH_JOB
7603 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007604 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7605 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7606 if (G_saved_tty_pgrp < 0)
7607 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007608
7609 /* try to dup stdin to high fd#, >= 255 */
7610 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7611 if (G_interactive_fd < 0) {
7612 /* try to dup to any fd */
7613 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007614 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007615 /* give up */
7616 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007617 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007618 }
7619 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007620// TODO: track & disallow any attempts of user
7621// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007622 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007623 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007624 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007625 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007626
Mike Frysinger38478a62009-05-20 04:48:06 -04007627 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007628 /* If we were run as 'hush &', sleep until we are
7629 * in the foreground (tty pgrp == our pgrp).
7630 * If we get started under a job aware app (like bash),
7631 * make sure we are now in charge so we don't fight over
7632 * who gets the foreground */
7633 while (1) {
7634 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007635 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7636 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007637 break;
7638 /* send TTIN to ourself (should stop us) */
7639 kill(- shell_pgrp, SIGTTIN);
7640 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007641 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007642
Denis Vlasenkof9375282009-04-05 19:13:39 +00007643 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007644 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007645
Mike Frysinger38478a62009-05-20 04:48:06 -04007646 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007647 /* Set other signals to restore saved_tty_pgrp */
7648 set_fatal_handlers();
7649 /* Put ourselves in our own process group
7650 * (bash, too, does this only if ctty is available) */
7651 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7652 /* Grab control of the terminal */
7653 tcsetpgrp(G_interactive_fd, getpid());
7654 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007655 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007656 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007657 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007658 } else {
7659 init_sigmasks();
7660 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007661#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007662 /* No job control compiled in, only prompt/line editing */
7663 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007664 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7665 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007666 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007667 G_interactive_fd = dup(STDIN_FILENO);
7668 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007669 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007670 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007671 }
7672 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007673 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007674 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007675 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007676 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007677#else
7678 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007679 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007680#endif
7681 /* bash:
7682 * if interactive but not a login shell, sources ~/.bashrc
7683 * (--norc turns this off, --rcfile <file> overrides)
7684 */
7685
7686 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007687 /* note: ash and hush share this string */
7688 printf("\n\n%s %s\n"
7689 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7690 "\n",
7691 bb_banner,
7692 "hush - the humble shell"
7693 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007694 }
7695
Denis Vlasenkof9375282009-04-05 19:13:39 +00007696 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007697
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007698 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007699#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007700 if (G.cwd != bb_msg_unknown)
7701 free((char*)G.cwd);
7702 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007703 while (cur_var) {
7704 struct variable *tmp = cur_var;
7705 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007706 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007707 cur_var = cur_var->next;
7708 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007709 }
Eric Andersen25f27032001-04-26 23:22:31 +00007710#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007711 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007712}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007713
7714
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007715#if ENABLE_MSH
7716int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7717int msh_main(int argc, char **argv)
7718{
7719 //bb_error_msg("msh is deprecated, please use hush instead");
7720 return hush_main(argc, argv);
7721}
7722#endif
7723
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007724
7725/*
7726 * Built-ins
7727 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007728static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007729{
7730 return 0;
7731}
7732
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007733static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007734{
7735 int argc = 0;
7736 while (*argv) {
7737 argc++;
7738 argv++;
7739 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007740 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007741}
7742
7743static int FAST_FUNC builtin_test(char **argv)
7744{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007745 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007746}
7747
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007748static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007749{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007750 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007751}
7752
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007753#if ENABLE_PRINTF
7754static int FAST_FUNC builtin_printf(char **argv)
7755{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007756 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007757}
7758#endif
7759
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007760static char **skip_dash_dash(char **argv)
7761{
7762 argv++;
7763 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7764 argv++;
7765 return argv;
7766}
7767
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007768static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007769{
7770 int rcode = EXIT_SUCCESS;
7771
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007772 argv = skip_dash_dash(argv);
7773 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007774 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007775 /* bash:
7776 * eval "echo Hi; done" ("done" is syntax error):
7777 * "echo Hi" will not execute too.
7778 */
7779 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007780 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007781 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007782 }
7783 return rcode;
7784}
7785
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007786static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007787{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007788 const char *newdir;
7789
7790 argv = skip_dash_dash(argv);
7791 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007792 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007793 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007794 * bash says "bash: cd: HOME not set" and does nothing
7795 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007796 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007797 const char *home = get_local_var_value("HOME");
7798 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007799 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007800 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007801 /* Mimic bash message exactly */
7802 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007803 return EXIT_FAILURE;
7804 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007805 /* Read current dir (get_cwd(1) is inside) and set PWD.
7806 * Note: do not enforce exporting. If PWD was unset or unexported,
7807 * set it again, but do not export. bash does the same.
7808 */
7809 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007810 return EXIT_SUCCESS;
7811}
7812
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007813static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007814{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007815 argv = skip_dash_dash(argv);
7816 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007817 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007818
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007819 /* Careful: we can end up here after [v]fork. Do not restore
7820 * tty pgrp then, only top-level shell process does that */
7821 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7822 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7823
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007824 /* TODO: if exec fails, bash does NOT exit! We do.
7825 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7826 * and tcsetpgrp, and this is inherently racy.
7827 */
7828 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007829}
7830
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007831static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007832{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007833 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007834
7835 /* interactive bash:
7836 * # trap "echo EEE" EXIT
7837 * # exit
7838 * exit
7839 * There are stopped jobs.
7840 * (if there are _stopped_ jobs, running ones don't count)
7841 * # exit
7842 * exit
7843 # EEE (then bash exits)
7844 *
7845 * we can use G.exiting = -1 as indicator "last cmd was exit"
7846 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007847
7848 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007849 argv = skip_dash_dash(argv);
7850 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007851 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007852 /* mimic bash: exit 123abc == exit 255 + error msg */
7853 xfunc_error_retval = 255;
7854 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007855 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007856}
7857
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007858static void print_escaped(const char *s)
7859{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007860 if (*s == '\'')
7861 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007862 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007863 const char *p = strchrnul(s, '\'');
7864 /* print 'xxxx', possibly just '' */
7865 printf("'%.*s'", (int)(p - s), s);
7866 if (*p == '\0')
7867 break;
7868 s = p;
7869 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007870 /* s points to '; print "'''...'''" */
7871 putchar('"');
7872 do putchar('\''); while (*++s == '\'');
7873 putchar('"');
7874 } while (*s);
7875}
7876
Denys Vlasenko295fef82009-06-03 12:47:26 +02007877#if !ENABLE_HUSH_LOCAL
7878#define helper_export_local(argv, exp, lvl) \
7879 helper_export_local(argv, exp)
7880#endif
7881static void helper_export_local(char **argv, int exp, int lvl)
7882{
7883 do {
7884 char *name = *argv;
7885
7886 /* So far we do not check that name is valid (TODO?) */
7887
7888 if (strchr(name, '=') == NULL) {
7889 struct variable *var;
7890
7891 var = get_local_var(name);
7892 if (exp == -1) { /* unexporting? */
7893 /* export -n NAME (without =VALUE) */
7894 if (var) {
7895 var->flg_export = 0;
7896 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7897 unsetenv(name);
7898 } /* else: export -n NOT_EXISTING_VAR: no-op */
7899 continue;
7900 }
7901 if (exp == 1) { /* exporting? */
7902 /* export NAME (without =VALUE) */
7903 if (var) {
7904 var->flg_export = 1;
7905 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7906 putenv(var->varstr);
7907 continue;
7908 }
7909 }
7910 /* Exporting non-existing variable.
7911 * bash does not put it in environment,
7912 * but remembers that it is exported,
7913 * and does put it in env when it is set later.
7914 * We just set it to "" and export. */
7915 /* Or, it's "local NAME" (without =VALUE).
7916 * bash sets the value to "". */
7917 name = xasprintf("%s=", name);
7918 } else {
7919 /* (Un)exporting/making local NAME=VALUE */
7920 name = xstrdup(name);
7921 }
7922 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7923 } while (*++argv);
7924}
7925
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007926static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007927{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007928 unsigned opt_unexport;
7929
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007930#if ENABLE_HUSH_EXPORT_N
7931 /* "!": do not abort on errors */
7932 opt_unexport = getopt32(argv, "!n");
7933 if (opt_unexport == (uint32_t)-1)
7934 return EXIT_FAILURE;
7935 argv += optind;
7936#else
7937 opt_unexport = 0;
7938 argv++;
7939#endif
7940
7941 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007942 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007943 if (e) {
7944 while (*e) {
7945#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007946 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007947#else
7948 /* ash emits: export VAR='VAL'
7949 * bash: declare -x VAR="VAL"
7950 * we follow ash example */
7951 const char *s = *e++;
7952 const char *p = strchr(s, '=');
7953
7954 if (!p) /* wtf? take next variable */
7955 continue;
7956 /* export var= */
7957 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007958 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007959 putchar('\n');
7960#endif
7961 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007962 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007963 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007964 return EXIT_SUCCESS;
7965 }
7966
Denys Vlasenko295fef82009-06-03 12:47:26 +02007967 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007968
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007969 return EXIT_SUCCESS;
7970}
7971
Denys Vlasenko295fef82009-06-03 12:47:26 +02007972#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007973static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007974{
7975 if (G.func_nest_level == 0) {
7976 bb_error_msg("%s: not in a function", argv[0]);
7977 return EXIT_FAILURE; /* bash compat */
7978 }
7979 helper_export_local(argv, 0, G.func_nest_level);
7980 return EXIT_SUCCESS;
7981}
7982#endif
7983
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007984static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007985{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007986 int sig;
7987 char *new_cmd;
7988
7989 if (!G.traps)
7990 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7991
7992 argv++;
7993 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007994 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007995 /* No args: print all trapped */
7996 for (i = 0; i < NSIG; ++i) {
7997 if (G.traps[i]) {
7998 printf("trap -- ");
7999 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008000 /* note: bash adds "SIG", but only if invoked
8001 * as "bash". If called as "sh", or if set -o posix,
8002 * then it prints short signal names.
8003 * We are printing short names: */
8004 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008005 }
8006 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008007 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008008 return EXIT_SUCCESS;
8009 }
8010
8011 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008012 /* If first arg is a number: reset all specified signals */
8013 sig = bb_strtou(*argv, NULL, 10);
8014 if (errno == 0) {
8015 int ret;
8016 process_sig_list:
8017 ret = EXIT_SUCCESS;
8018 while (*argv) {
8019 sig = get_signum(*argv++);
8020 if (sig < 0 || sig >= NSIG) {
8021 ret = EXIT_FAILURE;
8022 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008023 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008024 continue;
8025 }
8026
8027 free(G.traps[sig]);
8028 G.traps[sig] = xstrdup(new_cmd);
8029
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008030 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008031 get_signame(sig), sig, G.traps[sig]);
8032
8033 /* There is no signal for 0 (EXIT) */
8034 if (sig == 0)
8035 continue;
8036
8037 if (new_cmd) {
8038 sigaddset(&G.blocked_set, sig);
8039 } else {
8040 /* There was a trap handler, we are removing it
8041 * (if sig has non-DFL handling,
8042 * we don't need to do anything) */
8043 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8044 continue;
8045 sigdelset(&G.blocked_set, sig);
8046 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008047 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008048 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008049 return ret;
8050 }
8051
8052 if (!argv[1]) { /* no second arg */
8053 bb_error_msg("trap: invalid arguments");
8054 return EXIT_FAILURE;
8055 }
8056
8057 /* First arg is "-": reset all specified to default */
8058 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8059 /* Everything else: set arg as signal handler
8060 * (includes "" case, which ignores signal) */
8061 if (argv[0][0] == '-') {
8062 if (argv[0][1] == '\0') { /* "-" */
8063 /* new_cmd remains NULL: "reset these sigs" */
8064 goto reset_traps;
8065 }
8066 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8067 argv++;
8068 }
8069 /* else: "-something", no special meaning */
8070 }
8071 new_cmd = *argv;
8072 reset_traps:
8073 argv++;
8074 goto process_sig_list;
8075}
8076
Mike Frysinger93cadc22009-05-27 17:06:25 -04008077/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008078static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008079{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008080 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008081
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008082 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008083 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008084 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008085
8086 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008087 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008088 type = "an alias";*/
8089#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008090 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008091 type = "a function";
8092#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008093 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008094 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008095 else if ((path = find_in_path(*argv)) != NULL)
8096 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008097 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008098 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008099 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008100 continue;
8101 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008102
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008103 printf("%s is %s\n", *argv, type);
8104 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008105 }
8106
8107 return ret;
8108}
8109
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008110#if ENABLE_HUSH_JOB
8111/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008112static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008113{
8114 int i, jobnum;
8115 struct pipe *pi;
8116
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008117 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008118 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008119
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008120 /* If they gave us no args, assume they want the last backgrounded task */
8121 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008122 for (pi = G.job_list; pi; pi = pi->next) {
8123 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008124 goto found;
8125 }
8126 }
8127 bb_error_msg("%s: no current job", argv[0]);
8128 return EXIT_FAILURE;
8129 }
8130 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8131 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8132 return EXIT_FAILURE;
8133 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008134 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008135 if (pi->jobid == jobnum) {
8136 goto found;
8137 }
8138 }
8139 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8140 return EXIT_FAILURE;
8141 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008142 /* TODO: bash prints a string representation
8143 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008144 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008145 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008146 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008147 }
8148
8149 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008150 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8151 for (i = 0; i < pi->num_cmds; i++) {
8152 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8153 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008154 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008155 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008156
8157 i = kill(- pi->pgrp, SIGCONT);
8158 if (i < 0) {
8159 if (errno == ESRCH) {
8160 delete_finished_bg_job(pi);
8161 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008162 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008163 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008164 }
8165
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008166 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008167 remove_bg_job(pi);
8168 return checkjobs_and_fg_shell(pi);
8169 }
8170 return EXIT_SUCCESS;
8171}
8172#endif
8173
8174#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008175static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008176{
8177 const struct built_in_command *x;
8178
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008179 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008180 "Built-in commands:\n"
8181 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008182 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008183 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008184 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008185 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008186 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008187 return EXIT_SUCCESS;
8188}
8189#endif
8190
8191#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008192static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008193{
8194 struct pipe *job;
8195 const char *status_string;
8196
Denis Vlasenko87a86552008-07-29 19:43:10 +00008197 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008198 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008199 status_string = "Stopped";
8200 else
8201 status_string = "Running";
8202
8203 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8204 }
8205 return EXIT_SUCCESS;
8206}
8207#endif
8208
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008209#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008210static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008211{
8212 void *p;
8213 unsigned long l;
8214
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008215# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008216 /* Optional. Reduces probability of false positives */
8217 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008218# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008219 /* Crude attempt to find where "free memory" starts,
8220 * sans fragmentation. */
8221 p = malloc(240);
8222 l = (unsigned long)p;
8223 free(p);
8224 p = malloc(3400);
8225 if (l < (unsigned long)p) l = (unsigned long)p;
8226 free(p);
8227
8228 if (!G.memleak_value)
8229 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008230
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008231 l -= G.memleak_value;
8232 if ((long)l < 0)
8233 l = 0;
8234 l /= 1024;
8235 if (l > 127)
8236 l = 127;
8237
8238 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8239 return l;
8240}
8241#endif
8242
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008243static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008244{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008245 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008246 return EXIT_SUCCESS;
8247}
8248
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008249static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008250{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008251 const char *r;
8252 char *opt_n = NULL;
8253 char *opt_p = NULL;
8254 char *opt_t = NULL;
8255 char *opt_u = NULL;
8256 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008257
Denys Vlasenko03dad222010-01-12 23:29:57 +01008258 /* "!": do not abort on errors.
8259 * Option string must start with "sr" to match BUILTIN_READ_xxx
8260 */
8261 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8262 if (read_flags == (uint32_t)-1)
8263 return EXIT_FAILURE;
8264 argv += optind;
8265
8266 r = shell_builtin_read(set_local_var_from_halves,
8267 argv,
8268 get_local_var_value("IFS"), /* can be NULL */
8269 read_flags,
8270 opt_n,
8271 opt_p,
8272 opt_t,
8273 opt_u
8274 );
8275
8276 if ((uintptr_t)r > 1) {
8277 bb_error_msg("%s", r);
8278 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008279 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008280
Denys Vlasenko03dad222010-01-12 23:29:57 +01008281 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008282}
8283
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008284/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8285 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008286 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008287 * set [-abCefhmnuvx] [-o option] [argument...]
8288 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008289 * set -- [argument...]
8290 * set -o
8291 * set +o
8292 * Implementations shall support the options in both their hyphen and
8293 * plus-sign forms. These options can also be specified as options to sh.
8294 * Examples:
8295 * Write out all variables and their values: set
8296 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8297 * Turn on the -x and -v options: set -xv
8298 * Unset all positional parameters: set --
8299 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8300 * Set the positional parameters to the expansion of x, even if x expands
8301 * with a leading '-' or '+': set -- $x
8302 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008303 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008304 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008305static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008306{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008307 int n;
8308 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008309 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008310
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008311 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008312 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008313 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008314 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008315 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008316 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008317
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008318 do {
8319 if (!strcmp(arg, "--")) {
8320 ++argv;
8321 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008322 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008323 if (arg[0] != '+' && arg[0] != '-')
8324 break;
8325 for (n = 1; arg[n]; ++n)
8326 if (set_mode(arg[0], arg[n]))
8327 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008328 } while ((arg = *++argv) != NULL);
8329 /* Now argv[0] is 1st argument */
8330
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008331 if (arg == NULL)
8332 return EXIT_SUCCESS;
8333 set_argv:
8334
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008335 /* NB: G.global_argv[0] ($0) is never freed/changed */
8336 g_argv = G.global_argv;
8337 if (G.global_args_malloced) {
8338 pp = g_argv;
8339 while (*++pp)
8340 free(*pp);
8341 g_argv[1] = NULL;
8342 } else {
8343 G.global_args_malloced = 1;
8344 pp = xzalloc(sizeof(pp[0]) * 2);
8345 pp[0] = g_argv[0]; /* retain $0 */
8346 g_argv = pp;
8347 }
8348 /* This realloc's G.global_argv */
8349 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8350
8351 n = 1;
8352 while (*++pp)
8353 n++;
8354 G.global_argc = n;
8355
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008356 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008357
8358 /* Nothing known, so abort */
8359 error:
8360 bb_error_msg("set: %s: invalid option", arg);
8361 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008362}
8363
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008364static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008365{
8366 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008367 argv = skip_dash_dash(argv);
8368 if (argv[0]) {
8369 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008370 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008371 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008372 if (G.global_args_malloced) {
8373 int m = 1;
8374 while (m <= n)
8375 free(G.global_argv[m++]);
8376 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008377 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008378 memmove(&G.global_argv[1], &G.global_argv[n+1],
8379 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008380 return EXIT_SUCCESS;
8381 }
8382 return EXIT_FAILURE;
8383}
8384
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008385static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008386{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008387 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008388 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008389 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008390#if ENABLE_HUSH_FUNCTIONS
8391 smallint sv_flg;
8392#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008393
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008394 argv = skip_dash_dash(argv);
8395 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008396 if (!filename) {
8397 /* bash says: "bash: .: filename argument required" */
8398 return 2; /* bash compat */
8399 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008400 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008401 if (!strchr(filename, '/')) {
8402 arg_path = find_in_path(filename);
8403 if (arg_path)
8404 filename = arg_path;
8405 }
8406 input = fopen_or_warn(filename, "r");
8407 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008408 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008409 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008410 return EXIT_FAILURE;
8411 }
8412 close_on_exec_on(fileno(input));
8413
Mike Frysinger885b6f22009-04-18 21:04:25 +00008414#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008415 sv_flg = G.flag_return_in_progress;
8416 /* "we are inside sourced file, ok to use return" */
8417 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008418#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008419 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008420
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008421 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008422 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008423
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008424 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008425#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008426 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008427#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008428
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008429 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008430}
8431
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008432static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008433{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008434 int rc;
8435 mode_t mask;
8436
8437 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008438 argv = skip_dash_dash(argv);
8439 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008440 mode_t old_mask = mask;
8441
8442 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008443 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008444 mask ^= 0777;
8445 if (rc == 0) {
8446 mask = old_mask;
8447 /* bash messages:
8448 * bash: umask: 'q': invalid symbolic mode operator
8449 * bash: umask: 999: octal number out of range
8450 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008451 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008452 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008453 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008454 rc = 1;
8455 /* Mimic bash */
8456 printf("%04o\n", (unsigned) mask);
8457 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008458 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008459 umask(mask);
8460
8461 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008462}
8463
Mike Frysingerd690f682009-03-30 06:50:54 +00008464/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008465static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008466{
Mike Frysingerd690f682009-03-30 06:50:54 +00008467 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008468 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008469
Denis Vlasenko28e67962009-04-26 23:22:40 +00008470 /* "!": do not abort on errors */
8471 /* "+": stop at 1st non-option */
8472 opts = getopt32(argv, "!+vf");
8473 if (opts == (unsigned)-1)
8474 return EXIT_FAILURE;
8475 if (opts == 3) {
8476 bb_error_msg("unset: -v and -f are exclusive");
8477 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008478 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008479 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008480
8481 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008482 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008483 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008484 if (unset_local_var(*argv)) {
8485 /* unset <nonexistent_var> doesn't fail.
8486 * Error is when one tries to unset RO var.
8487 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008488 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008489 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008490 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008491#if ENABLE_HUSH_FUNCTIONS
8492 else {
8493 unset_func(*argv);
8494 }
8495#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008496 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008497 }
8498 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008499}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008500
Mike Frysinger56bdea12009-03-28 20:01:58 +00008501/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008502static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008503{
8504 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008505 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008506
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008507 argv = skip_dash_dash(argv);
8508 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008509 /* Don't care about wait results */
8510 /* Note 1: must wait until there are no more children */
8511 /* Note 2: must be interruptible */
8512 /* Examples:
8513 * $ sleep 3 & sleep 6 & wait
8514 * [1] 30934 sleep 3
8515 * [2] 30935 sleep 6
8516 * [1] Done sleep 3
8517 * [2] Done sleep 6
8518 * $ sleep 3 & sleep 6 & wait
8519 * [1] 30936 sleep 3
8520 * [2] 30937 sleep 6
8521 * [1] Done sleep 3
8522 * ^C <-- after ~4 sec from keyboard
8523 * $
8524 */
8525 sigaddset(&G.blocked_set, SIGCHLD);
8526 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8527 while (1) {
8528 checkjobs(NULL);
8529 if (errno == ECHILD)
8530 break;
8531 /* Wait for SIGCHLD or any other signal of interest */
8532 /* sigtimedwait with infinite timeout: */
8533 sig = sigwaitinfo(&G.blocked_set, NULL);
8534 if (sig > 0) {
8535 sig = check_and_run_traps(sig);
8536 if (sig && sig != SIGCHLD) { /* see note 2 */
8537 ret = 128 + sig;
8538 break;
8539 }
8540 }
8541 }
8542 sigdelset(&G.blocked_set, SIGCHLD);
8543 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8544 return ret;
8545 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008546
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008547 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008548 while (*argv) {
8549 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008550 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008551 /* mimic bash message */
8552 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008553 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008554 }
8555 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008556 if (WIFSIGNALED(status))
8557 ret = 128 + WTERMSIG(status);
8558 else if (WIFEXITED(status))
8559 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008560 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008561 ret = EXIT_FAILURE;
8562 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008563 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008564 ret = 127;
8565 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008566 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008567 }
8568
8569 return ret;
8570}
8571
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008572#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8573static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8574{
8575 if (argv[1]) {
8576 def = bb_strtou(argv[1], NULL, 10);
8577 if (errno || def < def_min || argv[2]) {
8578 bb_error_msg("%s: bad arguments", argv[0]);
8579 def = UINT_MAX;
8580 }
8581 }
8582 return def;
8583}
8584#endif
8585
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008586#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008587static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008588{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008589 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008590 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008591 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008592 return EXIT_SUCCESS; /* bash compat */
8593 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008594 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008595
8596 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8597 if (depth == UINT_MAX)
8598 G.flag_break_continue = BC_BREAK;
8599 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008600 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008601
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008602 return EXIT_SUCCESS;
8603}
8604
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008605static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008606{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008607 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8608 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008609}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008610#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008611
8612#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008613static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008614{
8615 int rc;
8616
8617 if (G.flag_return_in_progress != -1) {
8618 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8619 return EXIT_FAILURE; /* bash compat */
8620 }
8621
8622 G.flag_return_in_progress = 1;
8623
8624 /* bash:
8625 * out of range: wraps around at 256, does not error out
8626 * non-numeric param:
8627 * f() { false; return qwe; }; f; echo $?
8628 * bash: return: qwe: numeric argument required <== we do this
8629 * 255 <== we also do this
8630 */
8631 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8632 return rc;
8633}
8634#endif