blob: 3e8c387e7f04ccd5ae927daa4a451fc3f31e1983 [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 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001347 char *argv[3];
1348 /* argv[0] is unused */
1349 argv[1] = G.traps[0];
1350 argv[2] = NULL;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001351 G.traps[0] = NULL;
1352 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001353 builtin_eval(argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001354 /* free(argv[1]); - why bother */
Denis Vlasenkod5762932009-03-31 11:22:57 +00001355 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001356
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001357#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001358 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001359 sigexit(- (exitcode & 0xff));
1360#else
1361 exit(exitcode);
1362#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001363}
1364
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001365static int check_and_run_traps(int sig)
1366{
Dan Fandrichfdd7b562010-06-18 22:37:42 -07001367 static const struct timespec zero_timespec;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001368 smalluint save_rcode;
1369 int last_sig = 0;
1370
1371 if (sig)
1372 goto jump_in;
1373 while (1) {
1374 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1375 if (sig <= 0)
1376 break;
1377 jump_in:
1378 last_sig = sig;
1379 if (G.traps && G.traps[sig]) {
1380 if (G.traps[sig][0]) {
1381 /* We have user-defined handler */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001382 char *argv[3];
1383 /* argv[0] is unused */
1384 argv[1] = G.traps[sig];
1385 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001386 save_rcode = G.last_exitcode;
1387 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001388 G.last_exitcode = save_rcode;
1389 } /* else: "" trap, ignoring signal */
1390 continue;
1391 }
1392 /* not a trap: special action */
1393 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001394#if ENABLE_HUSH_FAST
1395 case SIGCHLD:
1396 G.count_SIGCHLD++;
1397//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1398 break;
1399#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001400 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001401 /* Builtin was ^C'ed, make it look prettier: */
1402 bb_putchar('\n');
1403 G.flag_SIGINT = 1;
1404 break;
1405#if ENABLE_HUSH_JOB
1406 case SIGHUP: {
1407 struct pipe *job;
1408 /* bash is observed to signal whole process groups,
1409 * not individual processes */
1410 for (job = G.job_list; job; job = job->next) {
1411 if (job->pgrp <= 0)
1412 continue;
1413 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1414 if (kill(- job->pgrp, SIGHUP) == 0)
1415 kill(- job->pgrp, SIGCONT);
1416 }
1417 sigexit(SIGHUP);
1418 }
1419#endif
1420 default: /* ignored: */
1421 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1422 break;
1423 }
1424 }
1425 return last_sig;
1426}
1427
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001428
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001429static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001430{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001431 if (force || G.cwd == NULL) {
1432 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1433 * we must not try to free(bb_msg_unknown) */
1434 if (G.cwd == bb_msg_unknown)
1435 G.cwd = NULL;
1436 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1437 if (!G.cwd)
1438 G.cwd = bb_msg_unknown;
1439 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001440 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001441}
1442
Denis Vlasenko83506862007-11-23 13:11:42 +00001443
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001444/*
1445 * Shell and environment variable support
1446 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001447static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001448{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001449 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001450 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001451
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001452 pp = &G.top_var;
1453 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001454 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001455 return pp;
1456 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001457 }
1458 return NULL;
1459}
1460
Denys Vlasenko03dad222010-01-12 23:29:57 +01001461static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001462{
Denys Vlasenko29082232010-07-16 13:52:32 +02001463 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001464 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001465
1466 if (G.expanded_assignments) {
1467 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001468 while (*cpp) {
1469 char *cp = *cpp;
1470 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1471 return cp + len + 1;
1472 cpp++;
1473 }
1474 }
1475
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001476 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001477 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001478 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001479
Denys Vlasenkodea47882009-10-09 15:40:49 +02001480 if (strcmp(name, "PPID") == 0)
1481 return utoa(G.root_ppid);
1482 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001483#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001484 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001485 return utoa(next_random(&G.random_gen));
1486#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001487 return NULL;
1488}
1489
1490/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001491 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001492 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001493 * 0: do not change export flag
1494 * (if creating new variable, flag will be 0)
1495 * 1: set export flag and putenv the variable
1496 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001497 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001498 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001499#if !BB_MMU && ENABLE_HUSH_LOCAL
1500/* all params are used */
1501#elif BB_MMU && ENABLE_HUSH_LOCAL
1502#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1503 set_local_var(str, flg_export, local_lvl)
1504#elif BB_MMU && !ENABLE_HUSH_LOCAL
1505#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001506 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001507#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, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001510#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001511static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001512{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001513 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001514 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001515 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001516 int name_len;
1517
Denis Vlasenko950bd722009-04-21 11:23:56 +00001518 eq_sign = strchr(str, '=');
1519 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001520 free(str);
1521 return -1;
1522 }
1523
Denis Vlasenko950bd722009-04-21 11:23:56 +00001524 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001525 var_pp = &G.top_var;
1526 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001527 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001528 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001529 continue;
1530 }
1531 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001532 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001533#if !BB_MMU
1534 if (!flg_read_only)
1535#endif
1536 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001537 free(str);
1538 return -1;
1539 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001540 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001541 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1542 *eq_sign = '\0';
1543 unsetenv(str);
1544 *eq_sign = '=';
1545 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001546#if ENABLE_HUSH_LOCAL
1547 if (cur->func_nest_level < local_lvl) {
1548 /* New variable is declared as local,
1549 * and existing one is global, or local
1550 * from enclosing function.
1551 * Remove and save old one: */
1552 *var_pp = cur->next;
1553 cur->next = *G.shadowed_vars_pp;
1554 *G.shadowed_vars_pp = cur;
1555 /* bash 3.2.33(1) and exported vars:
1556 * # export z=z
1557 * # f() { local z=a; env | grep ^z; }
1558 * # f
1559 * z=a
1560 * # env | grep ^z
1561 * z=z
1562 */
1563 if (cur->flg_export)
1564 flg_export = 1;
1565 break;
1566 }
1567#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001568 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001569 free_and_exp:
1570 free(str);
1571 goto exp;
1572 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001573 if (cur->max_len != 0) {
1574 if (cur->max_len >= strlen(str)) {
1575 /* This one is from startup env, reuse space */
1576 strcpy(cur->varstr, str);
1577 goto free_and_exp;
1578 }
1579 } else {
1580 /* max_len == 0 signifies "malloced" var, which we can
1581 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001582 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001583 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001584 cur->max_len = 0;
1585 goto set_str_and_exp;
1586 }
1587
Denys Vlasenko295fef82009-06-03 12:47:26 +02001588 /* Not found - create new variable struct */
1589 cur = xzalloc(sizeof(*cur));
1590#if ENABLE_HUSH_LOCAL
1591 cur->func_nest_level = local_lvl;
1592#endif
1593 cur->next = *var_pp;
1594 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001595
1596 set_str_and_exp:
1597 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001598#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001599 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001600#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001601 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001602 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001603 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001604 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1605 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001606 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001607 if (flg_export == -1) {
1608 cur->flg_export = 0;
1609 /* unsetenv was already done */
1610 } else {
1611 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1612 return putenv(cur->varstr);
1613 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001614 }
1615 return 0;
1616}
1617
Denys Vlasenko6db47842009-09-05 20:15:17 +02001618/* Used at startup and after each cd */
1619static void set_pwd_var(int exp)
1620{
1621 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1622 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1623}
1624
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001625static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001626{
1627 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001628 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001629
1630 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001631 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001632 var_pp = &G.top_var;
1633 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001634 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1635 if (cur->flg_read_only) {
1636 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001637 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001638 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001639 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001640 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1641 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001642 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1643 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001644 if (!cur->max_len)
1645 free(cur->varstr);
1646 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001647 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001648 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001649 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001650 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001651 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001652}
1653
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001654static int unset_local_var(const char *name)
1655{
1656 return unset_local_var_len(name, strlen(name));
1657}
1658
1659static void unset_vars(char **strings)
1660{
1661 char **v;
1662
1663 if (!strings)
1664 return;
1665 v = strings;
1666 while (*v) {
1667 const char *eq = strchrnul(*v, '=');
1668 unset_local_var_len(*v, (int)(eq - *v));
1669 v++;
1670 }
1671 free(strings);
1672}
1673
Denys Vlasenko03dad222010-01-12 23:29:57 +01001674static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001675{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001676 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001677 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001678}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001679
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001680
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001681/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001682 * Helpers for "var1=val1 var2=val2 cmd" feature
1683 */
1684static void add_vars(struct variable *var)
1685{
1686 struct variable *next;
1687
1688 while (var) {
1689 next = var->next;
1690 var->next = G.top_var;
1691 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001692 if (var->flg_export) {
1693 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001694 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001695 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001696 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001697 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001698 var = next;
1699 }
1700}
1701
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001702static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001703{
1704 char **s;
1705 struct variable *old = NULL;
1706
1707 if (!strings)
1708 return old;
1709 s = strings;
1710 while (*s) {
1711 struct variable *var_p;
1712 struct variable **var_pp;
1713 char *eq;
1714
1715 eq = strchr(*s, '=');
1716 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001717 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001718 if (var_pp) {
1719 /* Remove variable from global linked list */
1720 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001721 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001722 *var_pp = var_p->next;
1723 /* Add it to returned list */
1724 var_p->next = old;
1725 old = var_p;
1726 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001727 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001728 }
1729 s++;
1730 }
1731 return old;
1732}
1733
1734
1735/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001736 * in_str support
1737 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001738static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001739{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001740 int ch = *i->p;
1741 if (ch != '\0') {
1742 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001743 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001744 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001745 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001746}
1747
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001748static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001749{
1750 return *i->p;
1751}
1752
1753#if ENABLE_HUSH_INTERACTIVE
1754
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001755static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001756{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001757 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001758 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001759 if (G.PS1 == NULL)
1760 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001761 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001762 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001763 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001764 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001765 if (G.PS2 == NULL)
1766 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001767}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001768
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001769static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001770{
1771 const char *prompt_str;
1772 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001773 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1774 /* Set up the prompt */
1775 if (promptmode == 0) { /* PS1 */
1776 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001777 /* bash uses $PWD value, even if it is set by user.
1778 * It uses current dir only if PWD is unset.
1779 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001780 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001781 prompt_str = G.PS1;
1782 } else
1783 prompt_str = G.PS2;
1784 } else
1785 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001786 debug_printf("result '%s'\n", prompt_str);
1787 return prompt_str;
1788}
1789
1790static void get_user_input(struct in_str *i)
1791{
1792 int r;
1793 const char *prompt_str;
1794
1795 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001796# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001797 /* Enable command line editing only while a command line
1798 * is actually being read */
1799 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001800 G.flag_SIGINT = 0;
1801 /* buglet: SIGINT will not make new prompt to appear _at once_,
1802 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001803 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 +00001804 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001805 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001806 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001807 i->eof_flag = (r < 0);
1808 if (i->eof_flag) { /* EOF/error detected */
1809 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1810 G.user_input_buf[1] = '\0';
1811 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001812# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001813 do {
1814 G.flag_SIGINT = 0;
1815 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001816 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001817 G.user_input_buf[0] = r = fgetc(i->file);
1818 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001819//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001820 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001821 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001822# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001823 i->p = G.user_input_buf;
1824}
1825
1826#endif /* INTERACTIVE */
1827
1828/* This is the magic location that prints prompts
1829 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001830static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001831{
1832 int ch;
1833
1834 /* If there is data waiting, eat it up */
1835 if (i->p && *i->p) {
1836#if ENABLE_HUSH_INTERACTIVE
1837 take_cached:
1838#endif
1839 ch = *i->p++;
1840 if (i->eof_flag && !*i->p)
1841 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001842 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001843 } else {
1844 /* need to double check i->file because we might be doing something
1845 * more complicated by now, like sourcing or substituting. */
1846#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001847 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001848 do {
1849 get_user_input(i);
1850 } while (!*i->p); /* need non-empty line */
1851 i->promptmode = 1; /* PS2 */
1852 i->promptme = 0;
1853 goto take_cached;
1854 }
1855#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001856 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001857 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001858 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001859#if ENABLE_HUSH_INTERACTIVE
1860 if (ch == '\n')
1861 i->promptme = 1;
1862#endif
1863 return ch;
1864}
1865
Denis Vlasenko913a2012009-04-05 22:17:04 +00001866/* All callers guarantee this routine will never
1867 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001868 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001869static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001870{
1871 int ch;
1872 if (i->p && *i->p) {
1873 if (i->eof_flag && !i->p[1])
1874 return EOF;
1875 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001876 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001877 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001878 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001879 i->eof_flag = (ch == EOF);
1880 i->peek_buf[0] = ch;
1881 i->peek_buf[1] = '\0';
1882 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001883 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001884 return ch;
1885}
1886
1887static void setup_file_in_str(struct in_str *i, FILE *f)
1888{
1889 i->peek = file_peek;
1890 i->get = file_get;
1891#if ENABLE_HUSH_INTERACTIVE
1892 i->promptme = 1;
1893 i->promptmode = 0; /* PS1 */
1894#endif
1895 i->file = f;
1896 i->p = NULL;
1897}
1898
1899static void setup_string_in_str(struct in_str *i, const char *s)
1900{
1901 i->peek = static_peek;
1902 i->get = static_get;
1903#if ENABLE_HUSH_INTERACTIVE
1904 i->promptme = 1;
1905 i->promptmode = 0; /* PS1 */
1906#endif
1907 i->p = s;
1908 i->eof_flag = 0;
1909}
1910
1911
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001912/*
1913 * o_string support
1914 */
1915#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001916
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001917static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001918{
1919 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02001920 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001921 if (o->data)
1922 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001923}
1924
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001925static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001926{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001927 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001928 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001929}
1930
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001931static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1932{
1933 free(o->data);
1934}
1935
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001936static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001937{
1938 if (o->length + len > o->maxlen) {
1939 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1940 o->data = xrealloc(o->data, 1 + o->maxlen);
1941 }
1942}
1943
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001944static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001945{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001946 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1947 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001948 o->data[o->length] = ch;
1949 o->length++;
1950 o->data[o->length] = '\0';
1951}
1952
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001953static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001954{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001955 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001956 memcpy(&o->data[o->length], str, len);
1957 o->length += len;
1958 o->data[o->length] = '\0';
1959}
1960
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001961static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001962{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001963 o_addblock(o, str, strlen(str));
1964}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02001965
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001966#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001967static void nommu_addchr(o_string *o, int ch)
1968{
1969 if (o)
1970 o_addchr(o, ch);
1971}
1972#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001973# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001974#endif
1975
1976static void o_addstr_with_NUL(o_string *o, const char *str)
1977{
1978 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001979}
1980
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001981static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001982{
1983 while (len) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001984 len--;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02001985 o_addchr(o, *str);
1986 if (*str++ == '\\') {
1987 /* \z -> \\\z; \<eol> -> \\<eol> */
1988 o_addchr(o, '\\');
1989 if (len) {
1990 len--;
1991 o_addchr(o, '\\');
1992 o_addchr(o, *str++);
1993 }
1994 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001995 }
1996}
1997
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001998#undef HUSH_BRACE_EXP
1999/*
2000 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2001 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2002 * Apparently, on unquoted $v bash still does globbing
2003 * ("v='*.txt'; echo $v" prints all .txt files),
2004 * but NOT brace expansion! Thus, there should be TWO independent
2005 * quoting mechanisms on $v expansion side: one protects
2006 * $v from brace expansion, and other additionally protects "$v" against globbing.
2007 * We have only second one.
2008 */
2009
2010#ifdef HUSH_BRACE_EXP
2011# define MAYBE_BRACES "{}"
2012#else
2013# define MAYBE_BRACES ""
2014#endif
2015
Eric Andersen25f27032001-04-26 23:22:31 +00002016/* My analysis of quoting semantics tells me that state information
2017 * is associated with a destination, not a source.
2018 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002019static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002020{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002021 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002022 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002023 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002024 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002025 o_grow_by(o, sz);
2026 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002027 o->data[o->length] = '\\';
2028 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002029 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002030 o->data[o->length] = ch;
2031 o->length++;
2032 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002033}
2034
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002035static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002036{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002037 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002038 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002039 sz++;
2040 o->data[o->length] = '\\';
2041 o->length++;
2042 }
2043 o_grow_by(o, sz);
2044 o->data[o->length] = ch;
2045 o->length++;
2046 o->data[o->length] = '\0';
2047}
2048
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002049static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002050{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002051 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002052 char ch;
2053 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002054 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002055 if (ordinary_cnt > len) /* paranoia */
2056 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002057 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002058 if (ordinary_cnt == len)
2059 return;
2060 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002061 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002062
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002063 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002064 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002065 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002066 sz++;
2067 o->data[o->length] = '\\';
2068 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002069 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002070 o_grow_by(o, sz);
2071 o->data[o->length] = ch;
2072 o->length++;
2073 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002074 }
2075}
2076
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002077static void o_addQblock(o_string *o, const char *str, int len)
2078{
2079 if (!o->o_escape) {
2080 o_addblock(o, str, len);
2081 return;
2082 }
2083 o_addqblock(o, str, len);
2084}
2085
Denys Vlasenko38292b62010-09-05 14:49:40 +02002086static void o_addQstr(o_string *o, const char *str)
2087{
2088 o_addQblock(o, str, strlen(str));
2089}
2090
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002091/* A special kind of o_string for $VAR and `cmd` expansion.
2092 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002093 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002094 * list[i] contains an INDEX (int!) into this string data.
2095 * It means that if list[] needs to grow, data needs to be moved higher up
2096 * but list[i]'s need not be modified.
2097 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002098 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002099 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2100 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002101#if DEBUG_EXPAND || DEBUG_GLOB
2102static void debug_print_list(const char *prefix, o_string *o, int n)
2103{
2104 char **list = (char**)o->data;
2105 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2106 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002107
2108 indent();
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002109 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 +02002110 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 +00002111 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002112 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002113 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2114 o->data + (int)list[i] + string_start,
2115 o->data + (int)list[i] + string_start);
2116 i++;
2117 }
2118 if (n) {
2119 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002120 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002121 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002122 }
2123}
2124#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002125# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002126#endif
2127
2128/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2129 * in list[n] so that it points past last stored byte so far.
2130 * It returns n+1. */
2131static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002132{
2133 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002134 int string_start;
2135 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002136
2137 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002138 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2139 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002140 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002141 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002142 /* list[n] points to string_start, make space for 16 more pointers */
2143 o->maxlen += 0x10 * sizeof(list[0]);
2144 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002145 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002146 memmove(list + n + 0x10, list + n, string_len);
2147 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002148 } else {
2149 debug_printf_list("list[%d]=%d string_start=%d\n",
2150 n, string_len, string_start);
2151 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002152 } else {
2153 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002154 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2155 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002156 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2157 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002158 o->has_empty_slot = 0;
2159 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002160 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002161 return n + 1;
2162}
2163
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002164/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002165static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002166{
2167 char **list = (char**)o->data;
2168 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2169
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002170 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002171}
2172
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002173#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002174/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2175 * first, it processes even {a} (no commas), second,
2176 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002177 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002178 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002179
2180/* Helper */
2181static int glob_needed(const char *s)
2182{
2183 while (*s) {
2184 if (*s == '\\') {
2185 if (!s[1])
2186 return 0;
2187 s += 2;
2188 continue;
2189 }
2190 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2191 return 1;
2192 s++;
2193 }
2194 return 0;
2195}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002196/* Return pointer to next closing brace or to comma */
2197static const char *next_brace_sub(const char *cp)
2198{
2199 unsigned depth = 0;
2200 cp++;
2201 while (*cp != '\0') {
2202 if (*cp == '\\') {
2203 if (*++cp == '\0')
2204 break;
2205 cp++;
2206 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002207 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002208 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002209 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002210 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002211 depth++;
2212 }
2213
2214 return *cp != '\0' ? cp : NULL;
2215}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002216/* Recursive brace globber. Note: may garble pattern[]. */
2217static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002218{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002219 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002220 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002221 const char *next;
2222 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002223 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002224 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002225
2226 debug_printf_glob("glob_brace('%s')\n", pattern);
2227
2228 begin = pattern;
2229 while (1) {
2230 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002231 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002232 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002233 /* Find the first sub-pattern and at the same time
2234 * find the rest after the closing brace */
2235 next = next_brace_sub(begin);
2236 if (next == NULL) {
2237 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002238 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002239 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002240 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002241 /* "{abc}" with no commas - illegal
2242 * brace expr, disregard and skip it */
2243 begin = next + 1;
2244 continue;
2245 }
2246 break;
2247 }
2248 if (*begin == '\\' && begin[1] != '\0')
2249 begin++;
2250 begin++;
2251 }
2252 debug_printf_glob("begin:%s\n", begin);
2253 debug_printf_glob("next:%s\n", next);
2254
2255 /* Now find the end of the whole brace expression */
2256 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002257 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002258 rest = next_brace_sub(rest);
2259 if (rest == NULL) {
2260 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002261 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002262 }
2263 debug_printf_glob("rest:%s\n", rest);
2264 }
2265 rest_len = strlen(++rest) + 1;
2266
2267 /* We are sure the brace expression is well-formed */
2268
2269 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002270 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002271
2272 /* We have a brace expression. BEGIN points to the opening {,
2273 * NEXT points past the terminator of the first element, and REST
2274 * points past the final }. We will accumulate result names from
2275 * recursive runs for each brace alternative in the buffer using
2276 * GLOB_APPEND. */
2277
2278 p = begin + 1;
2279 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002280 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002281 memcpy(
2282 mempcpy(
2283 mempcpy(new_pattern_buf,
2284 /* We know the prefix for all sub-patterns */
2285 pattern, begin - pattern),
2286 p, next - p),
2287 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002288
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002289 /* Note: glob_brace() may garble new_pattern_buf[].
2290 * That's why we re-copy prefix every time (1st memcpy above).
2291 */
2292 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002293 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002294 /* We saw the last entry */
2295 break;
2296 }
2297 p = next + 1;
2298 next = next_brace_sub(next);
2299 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002300 free(new_pattern_buf);
2301 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002302
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002303 simple_glob:
2304 {
2305 int gr;
2306 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002307
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002308 memset(&globdata, 0, sizeof(globdata));
2309 gr = glob(pattern, 0, NULL, &globdata);
2310 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2311 if (gr != 0) {
2312 if (gr == GLOB_NOMATCH) {
2313 globfree(&globdata);
2314 /* NB: garbles parameter */
2315 unbackslash(pattern);
2316 o_addstr_with_NUL(o, pattern);
2317 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2318 return o_save_ptr_helper(o, n);
2319 }
2320 if (gr == GLOB_NOSPACE)
2321 bb_error_msg_and_die(bb_msg_memory_exhausted);
2322 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2323 * but we didn't specify it. Paranoia again. */
2324 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2325 }
2326 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2327 char **argv = globdata.gl_pathv;
2328 while (1) {
2329 o_addstr_with_NUL(o, *argv);
2330 n = o_save_ptr_helper(o, n);
2331 argv++;
2332 if (!*argv)
2333 break;
2334 }
2335 }
2336 globfree(&globdata);
2337 }
2338 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002339}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002340/* Performs globbing on last list[],
2341 * saving each result as a new list[].
2342 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002343static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002344{
2345 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002346
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002347 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002348 if (!o->data)
2349 return o_save_ptr_helper(o, n);
2350 pattern = o->data + o_get_last_ptr(o, n);
2351 debug_printf_glob("glob pattern '%s'\n", pattern);
2352 if (!glob_needed(pattern)) {
2353 /* unbackslash last string in o in place, fix length */
2354 o->length = unbackslash(pattern) - o->data;
2355 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2356 return o_save_ptr_helper(o, n);
2357 }
2358
2359 copy = xstrdup(pattern);
2360 /* "forget" pattern in o */
2361 o->length = pattern - o->data;
2362 n = glob_brace(copy, o, n);
2363 free(copy);
2364 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002365 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002366 return n;
2367}
2368
Denys Vlasenko8391c482010-05-22 17:50:43 +02002369#else /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002370
2371/* Helper */
2372static int glob_needed(const char *s)
2373{
2374 while (*s) {
2375 if (*s == '\\') {
2376 if (!s[1])
2377 return 0;
2378 s += 2;
2379 continue;
2380 }
2381 if (*s == '*' || *s == '[' || *s == '?')
2382 return 1;
2383 s++;
2384 }
2385 return 0;
2386}
2387/* Performs globbing on last list[],
2388 * saving each result as a new list[].
2389 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002390static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002391{
2392 glob_t globdata;
2393 int gr;
2394 char *pattern;
2395
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002396 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002397 if (!o->data)
2398 return o_save_ptr_helper(o, n);
2399 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002400 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002401 if (!glob_needed(pattern)) {
2402 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002403 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002404 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002405 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002406 return o_save_ptr_helper(o, n);
2407 }
2408
2409 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002410 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2411 * If we glob "*.\*" and don't find anything, we need
2412 * to fall back to using literal "*.*", but GLOB_NOCHECK
2413 * will return "*.\*"!
2414 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002415 gr = glob(pattern, 0, NULL, &globdata);
2416 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002417 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002418 if (gr == GLOB_NOMATCH) {
2419 globfree(&globdata);
2420 goto literal;
2421 }
2422 if (gr == GLOB_NOSPACE)
2423 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002424 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2425 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002426 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002427 }
2428 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2429 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002430 /* "forget" pattern in o */
2431 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002432 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002433 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002434 n = o_save_ptr_helper(o, n);
2435 argv++;
2436 if (!*argv)
2437 break;
2438 }
2439 }
2440 globfree(&globdata);
2441 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002442 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002443 return n;
2444}
2445
Denys Vlasenko8391c482010-05-22 17:50:43 +02002446#endif /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002447
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002448/* If o->o_glob == 1, glob the string so far remembered.
2449 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002450static int o_save_ptr(o_string *o, int n)
2451{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002452 if (o->o_glob) { /* if globbing is requested */
2453 /* If o->has_empty_slot, list[n] was already globbed
2454 * (if it was requested back then when it was filled)
2455 * so don't do that again! */
2456 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002457 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002458 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002459 return o_save_ptr_helper(o, n);
2460}
2461
2462/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002463static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002464{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002465 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002466 int string_start;
2467
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002468 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2469 if (DEBUG_EXPAND)
2470 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002471 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002472 list = (char**)o->data;
2473 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2474 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002475 while (n) {
2476 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002477 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002478 }
2479 return list;
2480}
2481
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002482static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002484/* Returns pi->next - next pipe in the list */
2485static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002486{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002487 struct pipe *next;
2488 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002489
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002490 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002491 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002492 struct command *command;
2493 struct redir_struct *r, *rnext;
2494
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002495 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002496 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002497 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002498 if (DEBUG_CLEAN) {
2499 int a;
2500 char **p;
2501 for (a = 0, p = command->argv; *p; a++, p++) {
2502 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2503 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002504 }
2505 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002506 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002507 }
2508 /* not "else if": on syntax error, we may have both! */
2509 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002510 debug_printf_clean(" begin group (cmd_type:%d)\n",
2511 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002512 free_pipe_list(command->group);
2513 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002514 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002515 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002516 /* else is crucial here.
2517 * If group != NULL, child_func is meaningless */
2518#if ENABLE_HUSH_FUNCTIONS
2519 else if (command->child_func) {
2520 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2521 command->child_func->parent_cmd = NULL;
2522 }
2523#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002524#if !BB_MMU
2525 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002526 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002527#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002528 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002529 debug_printf_clean(" redirect %d%s",
2530 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002531 /* guard against the case >$FOO, where foo is unset or blank */
2532 if (r->rd_filename) {
2533 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2534 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002535 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002536 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002537 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002538 rnext = r->next;
2539 free(r);
2540 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002541 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002542 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002543 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002544 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002545#if ENABLE_HUSH_JOB
2546 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002547 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002548#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002549
2550 next = pi->next;
2551 free(pi);
2552 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002553}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002554
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002555static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002557 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002558#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002559 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002560#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002561 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002562 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002563 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002564}
2565
2566
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002567/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002568
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002569static struct pipe *new_pipe(void)
2570{
Eric Andersen25f27032001-04-26 23:22:31 +00002571 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002572 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002573 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002574 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002575 return pi;
2576}
2577
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002578/* Command (member of a pipe) is complete, or we start a new pipe
2579 * if ctx->command is NULL.
2580 * No errors possible here.
2581 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002582static int done_command(struct parse_context *ctx)
2583{
2584 /* The command is really already in the pipe structure, so
2585 * advance the pipe counter and make a new, null command. */
2586 struct pipe *pi = ctx->pipe;
2587 struct command *command = ctx->command;
2588
2589 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002590 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002591 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002592 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002593 }
2594 pi->num_cmds++;
2595 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002596 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002597 } else {
2598 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2599 }
2600
2601 /* Only real trickiness here is that the uncommitted
2602 * command structure is not counted in pi->num_cmds. */
2603 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002604 ctx->command = command = &pi->cmds[pi->num_cmds];
2605 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002606 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002607 return pi->num_cmds; /* used only for 0/nonzero check */
2608}
2609
2610static void done_pipe(struct parse_context *ctx, pipe_style type)
2611{
2612 int not_null;
2613
2614 debug_printf_parse("done_pipe entered, followup %d\n", type);
2615 /* Close previous command */
2616 not_null = done_command(ctx);
2617 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002618#if HAS_KEYWORDS
2619 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2620 ctx->ctx_inverted = 0;
2621 ctx->pipe->res_word = ctx->ctx_res_w;
2622#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002623
2624 /* Without this check, even just <enter> on command line generates
2625 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002626 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002627 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002628#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002629 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002630#endif
2631#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002632 || ctx->ctx_res_w == RES_DONE
2633 || ctx->ctx_res_w == RES_FOR
2634 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002635#endif
2636#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002637 || ctx->ctx_res_w == RES_ESAC
2638#endif
2639 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002640 struct pipe *new_p;
2641 debug_printf_parse("done_pipe: adding new pipe: "
2642 "not_null:%d ctx->ctx_res_w:%d\n",
2643 not_null, ctx->ctx_res_w);
2644 new_p = new_pipe();
2645 ctx->pipe->next = new_p;
2646 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002647 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002648 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002649 * This is used to control execution.
2650 * RES_FOR and RES_IN are NOT sticky (needed to support
2651 * cases where variable or value happens to match a keyword):
2652 */
2653#if ENABLE_HUSH_LOOPS
2654 if (ctx->ctx_res_w == RES_FOR
2655 || ctx->ctx_res_w == RES_IN)
2656 ctx->ctx_res_w = RES_NONE;
2657#endif
2658#if ENABLE_HUSH_CASE
2659 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002660 ctx->ctx_res_w = RES_CASE_BODY;
2661 if (ctx->ctx_res_w == RES_CASE)
2662 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002663#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002664 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002665 /* Create the memory for command, roughly:
2666 * ctx->pipe->cmds = new struct command;
2667 * ctx->command = &ctx->pipe->cmds[0];
2668 */
2669 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002670 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002671 }
2672 debug_printf_parse("done_pipe return\n");
2673}
2674
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002675static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002676{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002677 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002678 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002679 /* Create the memory for command, roughly:
2680 * ctx->pipe->cmds = new struct command;
2681 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002682 */
2683 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002684}
2685
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002686/* If a reserved word is found and processed, parse context is modified
2687 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002688 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002689#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002690struct reserved_combo {
2691 char literal[6];
2692 unsigned char res;
2693 unsigned char assignment_flag;
2694 int flag;
2695};
2696enum {
2697 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002698# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002699 FLAG_IF = (1 << RES_IF ),
2700 FLAG_THEN = (1 << RES_THEN ),
2701 FLAG_ELIF = (1 << RES_ELIF ),
2702 FLAG_ELSE = (1 << RES_ELSE ),
2703 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002704# endif
2705# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002706 FLAG_FOR = (1 << RES_FOR ),
2707 FLAG_WHILE = (1 << RES_WHILE),
2708 FLAG_UNTIL = (1 << RES_UNTIL),
2709 FLAG_DO = (1 << RES_DO ),
2710 FLAG_DONE = (1 << RES_DONE ),
2711 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002712# endif
2713# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002714 FLAG_MATCH = (1 << RES_MATCH),
2715 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002716# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002717 FLAG_START = (1 << RES_XXXX ),
2718};
2719
2720static const struct reserved_combo* match_reserved_word(o_string *word)
2721{
Eric Andersen25f27032001-04-26 23:22:31 +00002722 /* Mostly a list of accepted follow-up reserved words.
2723 * FLAG_END means we are done with the sequence, and are ready
2724 * to turn the compound list into a command.
2725 * FLAG_START means the word must start a new compound list.
2726 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002727 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002728# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002729 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2730 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2731 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2732 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2733 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2734 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002735# endif
2736# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002737 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2738 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2739 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2740 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2741 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2742 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002743# endif
2744# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002745 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2746 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002747# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002748 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002749 const struct reserved_combo *r;
2750
2751 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2752 if (strcmp(word->data, r->literal) == 0)
2753 return r;
2754 }
2755 return NULL;
2756}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002757/* Return 0: not a keyword, 1: keyword
2758 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002759static int reserved_word(o_string *word, struct parse_context *ctx)
2760{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002761# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002762 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002763 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002764 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002765# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002766 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002767
Denys Vlasenko38292b62010-09-05 14:49:40 +02002768 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002769 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002770 r = match_reserved_word(word);
2771 if (!r)
2772 return 0;
2773
2774 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002775# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002776 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2777 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002778 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002779 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002780# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002781 if (r->flag == 0) { /* '!' */
2782 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002783 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002784 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002785 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002786 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002787 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002788 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002789 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002790 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002791
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002792 old = xmalloc(sizeof(*old));
2793 debug_printf_parse("push stack %p\n", old);
2794 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002795 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002796 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002797 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002798 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002799 ctx->ctx_res_w = RES_SNTX;
2800 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002801 } else {
2802 /* "{...} fi" is ok. "{...} if" is not
2803 * Example:
2804 * if { echo foo; } then { echo bar; } fi */
2805 if (ctx->command->group)
2806 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002807 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002808
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002809 ctx->ctx_res_w = r->res;
2810 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002811 word->o_assignment = r->assignment_flag;
2812
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002813 if (ctx->old_flag & FLAG_END) {
2814 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002815
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002816 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002817 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002818 old = ctx->stack;
2819 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002820 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002821# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002822 o_addstr(&old->as_string, ctx->as_string.data);
2823 o_free_unsafe(&ctx->as_string);
2824 old->command->group_as_string = xstrdup(old->as_string.data);
2825 debug_printf_parse("pop, remembering as:'%s'\n",
2826 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002827# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002828 *ctx = *old; /* physical copy */
2829 free(old);
2830 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002831 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002832}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002833#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00002834
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002835/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002836 * Normal return is 0. Syntax errors return 1.
2837 * Note: on return, word is reset, but not o_free'd!
2838 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002839static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002840{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002841 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00002842
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002843 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02002844 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002845 debug_printf_parse("done_word return 0: true null, ignored\n");
2846 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002847 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002848
Eric Andersen25f27032001-04-26 23:22:31 +00002849 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002850 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2851 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002852 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2853 * "2.7 Redirection
2854 * ...the word that follows the redirection operator
2855 * shall be subjected to tilde expansion, parameter expansion,
2856 * command substitution, arithmetic expansion, and quote
2857 * removal. Pathname expansion shall not be performed
2858 * on the word by a non-interactive shell; an interactive
2859 * shell may perform it, but shall do so only when
2860 * the expansion would result in one word."
2861 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002862 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002863 /* Cater for >\file case:
2864 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2865 * Same with heredocs:
2866 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2867 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002868 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2869 unbackslash(ctx->pending_redirect->rd_filename);
2870 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02002871 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002872 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2873 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002874 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002875 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002876 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002877 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002878 /* If this word wasn't an assignment, next ones definitely
2879 * can't be assignments. Even if they look like ones. */
2880 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2881 && word->o_assignment != WORD_IS_KEYWORD
2882 ) {
2883 word->o_assignment = NOT_ASSIGNMENT;
2884 } else {
2885 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2886 command->assignment_cnt++;
2887 word->o_assignment = MAYBE_ASSIGNMENT;
2888 }
2889
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002890#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002891# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00002892 if (ctx->ctx_dsemicolon
2893 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2894 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00002895 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002896 /* ctx->ctx_res_w = RES_MATCH; */
2897 ctx->ctx_dsemicolon = 0;
2898 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002899# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002900 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002901# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002902 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2903 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002904# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002905# if ENABLE_HUSH_CASE
2906 && ctx->ctx_res_w != RES_CASE
2907# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002908 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002909 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002910 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002911 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002912 debug_printf_parse("done_word return %d\n",
2913 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002914 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002915 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002916# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002917 if (strcmp(word->data, "[[") == 0) {
2918 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2919 }
2920 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002921# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002922 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002923#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00002924 if (command->group) {
2925 /* "{ echo foo; } echo bar" - bad */
2926 syntax_error_at(word->data);
2927 debug_printf_parse("done_word return 1: syntax error, "
2928 "groups and arglists don't mix\n");
2929 return 1;
2930 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02002931 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00002932 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2933 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002934 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002935 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002936 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002937 char *p = word->data;
2938 while (p[0] == SPECIAL_VAR_SYMBOL
2939 && (p[1] & 0x7f) == '@'
2940 && p[2] == SPECIAL_VAR_SYMBOL
2941 ) {
2942 p += 3;
2943 }
2944 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002945 /* saw no "$@", or not only "$@" but some
2946 * real text is there too */
2947 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002948 * e.g. "", $empty"" etc to not disappear */
2949 o_addchr(word, SPECIAL_VAR_SYMBOL);
2950 o_addchr(word, SPECIAL_VAR_SYMBOL);
2951 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002952 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002953 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002954 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002955 }
Eric Andersen25f27032001-04-26 23:22:31 +00002956
Denis Vlasenko06810332007-05-21 23:30:54 +00002957#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002958 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02002959 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002960 || !is_well_formed_var_name(command->argv[0], '\0')
2961 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002962 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002963 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002964 return 1;
2965 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002966 /* Force FOR to have just one word (variable name) */
2967 /* NB: basically, this makes hush see "for v in ..."
2968 * syntax as if it is "for v; in ...". FOR and IN become
2969 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002970 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002971 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002972#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002973#if ENABLE_HUSH_CASE
2974 /* Force CASE to have just one word */
2975 if (ctx->ctx_res_w == RES_CASE) {
2976 done_pipe(ctx, PIPE_SEQ);
2977 }
2978#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002979
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002980 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002981
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002982 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002983 return 0;
2984}
2985
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002986
2987/* Peek ahead in the input to find out if we have a "&n" construct,
2988 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002989 * Return:
2990 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
2991 * REDIRFD_SYNTAX_ERR if syntax error,
2992 * REDIRFD_TO_FILE if no & was seen,
2993 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002994 */
2995#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002996#define parse_redir_right_fd(as_string, input) \
2997 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002998#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002999static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003000{
3001 int ch, d, ok;
3002
3003 ch = i_peek(input);
3004 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003005 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003006
3007 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003008 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003009 ch = i_peek(input);
3010 if (ch == '-') {
3011 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003012 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003013 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003014 }
3015 d = 0;
3016 ok = 0;
3017 while (ch != EOF && isdigit(ch)) {
3018 d = d*10 + (ch-'0');
3019 ok = 1;
3020 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003021 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003022 ch = i_peek(input);
3023 }
3024 if (ok) return d;
3025
3026//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3027
3028 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003029 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003030}
3031
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003032/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003033 */
3034static int parse_redirect(struct parse_context *ctx,
3035 int fd,
3036 redir_type style,
3037 struct in_str *input)
3038{
3039 struct command *command = ctx->command;
3040 struct redir_struct *redir;
3041 struct redir_struct **redirp;
3042 int dup_num;
3043
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003044 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003045 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003046 /* Check for a '>&1' type redirect */
3047 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3048 if (dup_num == REDIRFD_SYNTAX_ERR)
3049 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003050 } else {
3051 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003052 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003053 if (dup_num) { /* <<-... */
3054 ch = i_getch(input);
3055 nommu_addchr(&ctx->as_string, ch);
3056 ch = i_peek(input);
3057 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003058 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003059
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003060 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003061 int ch = i_peek(input);
3062 if (ch == '|') {
3063 /* >|FILE redirect ("clobbering" >).
3064 * Since we do not support "set -o noclobber" yet,
3065 * >| and > are the same for now. Just eat |.
3066 */
3067 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003068 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003069 }
3070 }
3071
3072 /* Create a new redir_struct and append it to the linked list */
3073 redirp = &command->redirects;
3074 while ((redir = *redirp) != NULL) {
3075 redirp = &(redir->next);
3076 }
3077 *redirp = redir = xzalloc(sizeof(*redir));
3078 /* redir->next = NULL; */
3079 /* redir->rd_filename = NULL; */
3080 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003081 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003082
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003083 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3084 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003085
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003086 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003087 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003088 /* Erik had a check here that the file descriptor in question
3089 * is legit; I postpone that to "run time"
3090 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003091 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3092 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003093 } else {
3094 /* Set ctx->pending_redirect, so we know what to do at the
3095 * end of the next parsed word. */
3096 ctx->pending_redirect = redir;
3097 }
3098 return 0;
3099}
3100
Eric Andersen25f27032001-04-26 23:22:31 +00003101/* If a redirect is immediately preceded by a number, that number is
3102 * supposed to tell which file descriptor to redirect. This routine
3103 * looks for such preceding numbers. In an ideal world this routine
3104 * needs to handle all the following classes of redirects...
3105 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3106 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3107 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3108 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003109 *
3110 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3111 * "2.7 Redirection
3112 * ... If n is quoted, the number shall not be recognized as part of
3113 * the redirection expression. For example:
3114 * echo \2>a
3115 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003116 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003117 *
3118 * A -1 return means no valid number was found,
3119 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003120 */
3121static int redirect_opt_num(o_string *o)
3122{
3123 int num;
3124
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003125 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003126 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003127 num = bb_strtou(o->data, NULL, 10);
3128 if (errno || num < 0)
3129 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003130 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003131 return num;
3132}
3133
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003134#if BB_MMU
3135#define fetch_till_str(as_string, input, word, skip_tabs) \
3136 fetch_till_str(input, word, skip_tabs)
3137#endif
3138static char *fetch_till_str(o_string *as_string,
3139 struct in_str *input,
3140 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003141 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003142{
3143 o_string heredoc = NULL_O_STRING;
3144 int past_EOL = 0;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003145 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003146 int ch;
3147
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003148 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003149 while (1) {
3150 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003151 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003152 if (ch == '\n'
Denys Vlasenko83b900f2010-09-06 11:47:55 +02003153 /* TODO: or EOF? (heredoc delimiter may end with <eof>, not only <eol>) */
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003154 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3155 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003156 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3157 heredoc.data[past_EOL] = '\0';
3158 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3159 return heredoc.data;
3160 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003161 do {
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003162 o_addchr(&heredoc, '\n');
3163 prev = 0; /* not \ */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003164 past_EOL = heredoc.length;
3165 jump_in:
3166 do {
3167 ch = i_getch(input);
3168 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003169 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003170 } while (ch == '\n');
3171 }
3172 if (ch == EOF) {
3173 o_free_unsafe(&heredoc);
3174 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003175 }
3176 o_addchr(&heredoc, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003177 if (prev == '\\' && ch == '\\')
3178 /* Correctly handle foo\\<eol> (not a line cont.) */
3179 prev = 0; /* not \ */
3180 else
3181 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003182 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003183 }
3184}
3185
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003186/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3187 * and load them all. There should be exactly heredoc_cnt of them.
3188 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003189static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3190{
3191 struct pipe *pi = ctx->list_head;
3192
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003193 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003194 int i;
3195 struct command *cmd = pi->cmds;
3196
3197 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3198 pi->num_cmds,
3199 cmd->argv ? cmd->argv[0] : "NONE");
3200 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003201 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003202
3203 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3204 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003205 while (redir) {
3206 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003207 char *p;
3208
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003209 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003210 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003211 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003212 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003213 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003214 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003215 return 1;
3216 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003217 free(redir->rd_filename);
3218 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003219 heredoc_cnt--;
3220 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003221 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003222 }
3223 cmd++;
3224 }
3225 pi = pi->next;
3226 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003227#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003228 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003229 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003230 bb_error_msg_and_die("heredoc BUG 2");
3231#endif
3232 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003233}
3234
3235
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003236static int run_list(struct pipe *pi);
3237#if BB_MMU
3238#define parse_stream(pstring, input, end_trigger) \
3239 parse_stream(input, end_trigger)
3240#endif
3241static struct pipe *parse_stream(char **pstring,
3242 struct in_str *input,
3243 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003244
Eric Andersen25f27032001-04-26 23:22:31 +00003245
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003246#if !ENABLE_HUSH_FUNCTIONS
3247#define parse_group(dest, ctx, input, ch) \
3248 parse_group(ctx, input, ch)
3249#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003250static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003251 struct in_str *input, int ch)
3252{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003253 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003254 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003255 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003256 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003257 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003258 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003259
3260 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003261#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003262 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003263 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003264 if (done_word(dest, ctx))
3265 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003266 if (!command->argv)
3267 goto skip; /* (... */
3268 if (command->argv[1]) { /* word word ... (... */
3269 syntax_error_unexpected_ch('(');
3270 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003271 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003272 /* it is "word(..." or "word (..." */
3273 do
3274 ch = i_getch(input);
3275 while (ch == ' ' || ch == '\t');
3276 if (ch != ')') {
3277 syntax_error_unexpected_ch(ch);
3278 return 1;
3279 }
3280 nommu_addchr(&ctx->as_string, ch);
3281 do
3282 ch = i_getch(input);
3283 while (ch == ' ' || ch == '\t' || ch == '\n');
3284 if (ch != '{') {
3285 syntax_error_unexpected_ch(ch);
3286 return 1;
3287 }
3288 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003289 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003290 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003291 }
3292#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003293
3294#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003295 if (command->argv /* word [word]{... */
3296 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003297 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003298 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003299 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003300 debug_printf_parse("parse_group return 1: "
3301 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003302 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003303 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003304#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003305
3306#if ENABLE_HUSH_FUNCTIONS
3307 skip:
3308#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003309 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003310 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003311 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003312 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003313 } else {
3314 /* bash does not allow "{echo...", requires whitespace */
3315 ch = i_getch(input);
3316 if (ch != ' ' && ch != '\t' && ch != '\n') {
3317 syntax_error_unexpected_ch(ch);
3318 return 1;
3319 }
3320 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003321 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003322
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003323 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003324#if BB_MMU
3325# define as_string NULL
3326#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003327 char *as_string = NULL;
3328#endif
3329 pipe_list = parse_stream(&as_string, input, endch);
3330#if !BB_MMU
3331 if (as_string)
3332 o_addstr(&ctx->as_string, as_string);
3333#endif
3334 /* empty ()/{} or parse error? */
3335 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003336 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003337 if (!BB_MMU)
3338 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003339 debug_printf_parse("parse_group return 1: "
3340 "parse_stream returned %p\n", pipe_list);
3341 return 1;
3342 }
3343 command->group = pipe_list;
3344#if !BB_MMU
3345 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3346 command->group_as_string = as_string;
3347 debug_printf_parse("end of group, remembering as:'%s'\n",
3348 command->group_as_string);
3349#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003350#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003351 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003352 debug_printf_parse("parse_group return 0\n");
3353 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003354 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003355}
3356
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003357#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003358/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003359static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003360/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003361static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003362{
3363 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003364 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003365 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003366 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003367 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003368 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003369 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003370 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003371 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003372 }
3373}
3374/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003375static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003376{
3377 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003378 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003379 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003380 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003381 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003382 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003383 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003384 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003385 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003386 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003387 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003388 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003389 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003390 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003391 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003392 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003393 continue;
3394 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003395 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003396 }
3397}
3398/* Process `cmd` - copy contents until "`" is seen. Complicated by
3399 * \` quoting.
3400 * "Within the backquoted style of command substitution, backslash
3401 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3402 * The search for the matching backquote shall be satisfied by the first
3403 * backquote found without a preceding backslash; during this search,
3404 * if a non-escaped backquote is encountered within a shell comment,
3405 * a here-document, an embedded command substitution of the $(command)
3406 * form, or a quoted string, undefined results occur. A single-quoted
3407 * or double-quoted string that begins, but does not end, within the
3408 * "`...`" sequence produces undefined results."
3409 * Example Output
3410 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3411 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003412static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003413{
3414 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003415 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003416 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003417 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003418 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003419 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003420 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003421 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003422 if (ch == '\\') {
3423 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003424 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003425 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003426 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003427 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003428 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003429 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003430 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003431 ch = ch2;
3432 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003433 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003434 }
3435}
3436/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3437 * quoting and nested ()s.
3438 * "With the $(command) style of command substitution, all characters
3439 * following the open parenthesis to the matching closing parenthesis
3440 * constitute the command. Any valid shell script can be used for command,
3441 * except a script consisting solely of redirections which produces
3442 * unspecified results."
3443 * Example Output
3444 * echo $(echo '(TEST)' BEST) (TEST) BEST
3445 * echo $(echo 'TEST)' BEST) TEST) BEST
3446 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003447 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003448 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003449 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003450 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3451 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003452 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003453#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003454static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003455{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003456 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003457 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003458# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003459 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003460# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003461 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3462
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003463 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003464 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003465 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003466 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003467 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003468 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003469 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003470 if (!dbl)
3471 break;
3472 /* we look for closing )) of $((EXPR)) */
3473 if (i_peek(input) == end_ch) {
3474 i_getch(input); /* eat second ')' */
3475 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003476 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003477 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003478 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003479 if (ch == '(' || ch == '{') {
3480 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003481 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003482 o_addchr(dest, ch);
3483 continue;
3484 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003485 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003486 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003487 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003488 continue;
3489 }
3490 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003491 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003492 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003493 continue;
3494 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003495 if (ch == '`') {
3496 add_till_backquote(dest, input);
3497 o_addchr(dest, ch);
3498 continue;
3499 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003500 if (ch == '\\') {
3501 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003502 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003503 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003504 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003505 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003506 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003507 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003508 continue;
3509 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003510 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003511 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003512}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003513#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003514
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003515/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003516#if BB_MMU
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003517#define parse_dollar(as_string, dest, input) \
3518 parse_dollar(dest, input)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003519#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003520#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003521static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003522 o_string *dest,
3523 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003524{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003525 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003526 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003527
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003528 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003529 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003530 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003531 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003532 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003533 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003534 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003535 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003536 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003537 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003538 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003539 if (!isalnum(ch) && ch != '_')
3540 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003541 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003542 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003543 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003544 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003545 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003546 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003547 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003548 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003549 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003550 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003551 o_addchr(dest, ch | quote_mask);
3552 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003553 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003554 case '$': /* pid */
3555 case '!': /* last bg pid */
3556 case '?': /* last exit code */
3557 case '#': /* number of args */
3558 case '*': /* args */
3559 case '@': /* args */
3560 goto make_one_char_var;
3561 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003562 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3563
Denys Vlasenko74369502010-05-21 19:52:01 +02003564 ch = i_getch(input); /* eat '{' */
3565 nommu_addchr(as_string, ch);
3566
3567 ch = i_getch(input); /* first char after '{' */
3568 nommu_addchr(as_string, ch);
3569 /* It should be ${?}, or ${#var},
3570 * or even ${?+subst} - operator acting on a special variable,
3571 * or the beginning of variable name.
3572 */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02003573 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
Denys Vlasenko74369502010-05-21 19:52:01 +02003574 bad_dollar_syntax:
3575 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003576 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003577 return 1;
3578 }
3579 ch |= quote_mask;
3580
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003581 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003582 * However, this regresses some of our testsuite cases
3583 * which check invalid constructs like ${%}.
3584 * Oh well... let's check that the var name part is fine... */
3585
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003586 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003587 unsigned pos;
3588
Denys Vlasenko74369502010-05-21 19:52:01 +02003589 o_addchr(dest, ch);
3590 debug_printf_parse(": '%c'\n", ch);
3591
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003592 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003593 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003594 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003595 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003596
Denys Vlasenko74369502010-05-21 19:52:01 +02003597 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003598 unsigned end_ch;
3599 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003600 /* handle parameter expansions
3601 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3602 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003603 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003604 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003605
3606 /* Eat everything until closing '}' (or ':') */
3607 end_ch = '}';
3608 if (ENABLE_HUSH_BASH_COMPAT
3609 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003610 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003611 ) {
3612 /* It's ${var:N[:M]} thing */
3613 end_ch = '}' * 0x100 + ':';
3614 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003615 if (ENABLE_HUSH_BASH_COMPAT
3616 && ch == '/'
3617 ) {
3618 /* It's ${var/[/]pattern[/repl]} thing */
3619 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3620 i_getch(input);
3621 nommu_addchr(as_string, '/');
3622 ch = '\\';
3623 }
3624 end_ch = '}' * 0x100 + '/';
3625 }
3626 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003627 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003628 if (!BB_MMU)
3629 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003630#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003631 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003632#else
3633#error Simple code to only allow ${var} is not implemented
3634#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003635 if (as_string) {
3636 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003637 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003638 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003639
3640 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3641 /* close the first block: */
3642 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003643 /* while parsing N from ${var:N[:M]}
3644 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003645 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003646 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003647 end_ch = '}';
3648 goto again;
3649 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003650 /* got '}' */
3651 if (end_ch == '}' * 0x100 + ':') {
3652 /* it's ${var:N} - emulate :999999999 */
3653 o_addstr(dest, "999999999");
3654 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003655 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003656 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003657 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003658 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003659 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3660 break;
3661 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003662#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003663 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003664 unsigned pos;
3665
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003666 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003667 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003668# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003669 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003670 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003671 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3673 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003674 if (!BB_MMU)
3675 pos = dest->length;
3676 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003677 if (as_string) {
3678 o_addstr(as_string, dest->data + pos);
3679 o_addchr(as_string, ')');
3680 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003681 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003682 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003683 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003684 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003685# endif
3686# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003687 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3688 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003689 if (!BB_MMU)
3690 pos = dest->length;
3691 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003692 if (as_string) {
3693 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003694 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003695 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003696 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003697# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003698 break;
3699 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003700#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003701 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003702 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003703 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003704 ch = i_peek(input);
3705 if (isalnum(ch)) { /* it's $_name or $_123 */
3706 ch = '_';
3707 goto make_var;
3708 }
3709 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003710 /* TODO: $_ and $-: */
3711 /* $_ Shell or shell script name; or last argument of last command
3712 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3713 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003714 /* $- Option flags set by set builtin or shell options (-i etc) */
3715 default:
3716 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003717 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003718 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003719 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003720#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003721}
3722
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003723#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003724#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003725 parse_stream_dquoted(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003726#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003727#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003728static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003729 o_string *dest,
3730 struct in_str *input,
3731 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003732{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003733 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003734 int next;
3735
3736 again:
3737 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003738 if (ch != EOF)
3739 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003740 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003741 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003742 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003743 debug_printf_parse("parse_stream_dquoted return 0\n");
3744 return 0;
3745 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003746 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003747 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003748 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003749 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003750 }
3751 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003752 if (ch != '\n') {
3753 next = i_peek(input);
3754 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003755 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003756 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003757 if (ch == '\\') {
3758 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003759 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003760 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003761 }
3762 /* bash:
3763 * "The backslash retains its special meaning [in "..."]
3764 * only when followed by one of the following characters:
3765 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003766 * within double quotes by preceding it with a backslash."
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003767 * NB: in (unquoted) heredoc, above does not apply to ".
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003768 */
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003769 if (next == dquote_end || strchr("$`\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00003770 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02003771 if (ch != '\n') {
3772 o_addqchr(dest, ch);
3773 nommu_addchr(as_string, ch);
3774 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003775 } else {
3776 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00003777 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003778 }
3779 goto again;
3780 }
3781 if (ch == '$') {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003782 if (parse_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003783 debug_printf_parse("parse_stream_dquoted return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003784 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003785 return 1;
3786 }
3787 goto again;
3788 }
3789#if ENABLE_HUSH_TICK
3790 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003791 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003792 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3793 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003794 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003795 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3796 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003797 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003798 }
3799#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003800 o_addQchr(dest, ch);
3801 if (ch == '='
3802 && (dest->o_assignment == MAYBE_ASSIGNMENT
3803 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003804 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00003805 ) {
3806 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3807 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003808 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003809#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003810}
3811
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003812/*
3813 * Scan input until EOF or end_trigger char.
3814 * Return a list of pipes to execute, or NULL on EOF
3815 * or if end_trigger character is met.
3816 * On syntax error, exit is shell is not interactive,
3817 * reset parsing machinery and start parsing anew,
3818 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003819 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003820static struct pipe *parse_stream(char **pstring,
3821 struct in_str *input,
3822 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003823{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003824 struct parse_context ctx;
3825 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003826 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003827 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00003828
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003829 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00003830 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003831 * found. When recursing, quote state is passed in via dest->o_escape.
3832 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003833 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02003834 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003835 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003836
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003837 /* If very first arg is "" or '', dest.data may end up NULL.
3838 * Preventing this: */
3839 o_addchr(&dest, '\0');
3840 dest.length = 0;
3841
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003842 G.ifs = get_local_var_value("IFS");
3843 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01003844 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003845
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003846 reset:
3847#if ENABLE_HUSH_INTERACTIVE
3848 input->promptmode = 0; /* PS1 */
3849#endif
3850 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
3851 initialize_context(&ctx);
3852 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003853 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003854 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003855 const char *is_ifs;
3856 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003857 int ch;
3858 int next;
3859 int redir_fd;
3860 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003861
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003862 if (is_in_dquote) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003863 /* dest.has_quoted_part = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003864 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003865 goto parse_error;
3866 }
3867 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003868 is_in_dquote = 0;
3869 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003870 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003871 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3872 ch, ch, dest.o_escape);
3873 if (ch == EOF) {
3874 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003875
3876 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003877 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003878 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003879 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003880 /* end_trigger == '}' case errors out earlier,
3881 * checking only ')' */
3882 if (end_trigger == ')') {
3883 syntax_error_unterm_ch('('); /* exits */
3884 /* goto parse_error; */
3885 }
3886
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003887 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003888 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003889 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003890 o_free(&dest);
3891 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003892 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003893 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003894 /* (this makes bare "&" cmd a no-op.
3895 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003896 if (pi->num_cmds == 0
3897 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3898 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003899 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003900 pi = NULL;
3901 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003902#if !BB_MMU
3903 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3904 if (pstring)
3905 *pstring = ctx.as_string.data;
3906 else
3907 o_free_unsafe(&ctx.as_string);
3908#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003909 debug_leave();
3910 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003911 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003912 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003913 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003914
3915 next = '\0';
3916 if (ch != '\n')
3917 next = i_peek(input);
3918
3919 is_special = "{}<>;&|()#'" /* special outside of "str" */
3920 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3921 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003922 if (ctx.command->argv /* word [word]{... - non-special */
3923 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003924 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003925 || (next != ';' /* }; - special */
3926 && next != ')' /* }) - special */
3927 && next != '&' /* }& and }&& ... - special */
3928 && next != '|' /* }|| ... - special */
3929 && !strchr(G.ifs, next) /* {word - non-special */
3930 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003931 ) {
3932 /* They are not special, skip "{}" */
3933 is_special += 2;
3934 }
3935 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003936 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003937
3938 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003939 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003940 o_addQchr(&dest, ch);
3941 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3942 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003943 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003944 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00003945 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003946 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003947 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003948 continue;
3949 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00003950
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003951 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003952 if (done_word(&dest, &ctx)) {
3953 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00003954 }
Denis Vlasenko37181682009-04-03 03:19:15 +00003955 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003956#if ENABLE_HUSH_CASE
3957 /* "case ... in <newline> word) ..." -
3958 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003959 if (ctx.command->argv == NULL
3960 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00003961 ) {
3962 continue;
3963 }
3964#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003965 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003966 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003967 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3968 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003969 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003970 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003971 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003972 heredoc_cnt = 0;
3973 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003974 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003975 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00003976 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003977 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003978 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003979 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00003980
3981 /* "cmd}" or "cmd }..." without semicolon or &:
3982 * } is an ordinary char in this case, even inside { cmd; }
3983 * Pathological example: { ""}; } should exec "}" cmd
3984 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00003985 if (ch == '}') {
3986 if (!IS_NULL_CMD(ctx.command) /* cmd } */
3987 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003988 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00003989 ) {
3990 goto ordinary_char;
3991 }
3992 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
3993 goto skip_end_trigger;
3994 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00003995 }
3996
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003997 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003998 && (ch != ';' || heredoc_cnt == 0)
3999#if ENABLE_HUSH_CASE
4000 && (ch != ')'
4001 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004002 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004003 )
4004#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004005 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004006 if (heredoc_cnt) {
4007 /* This is technically valid:
4008 * { cat <<HERE; }; echo Ok
4009 * heredoc
4010 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004011 * HERE
4012 * but we don't support this.
4013 * We require heredoc to be in enclosing {}/(),
4014 * if any.
4015 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004016 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004017 goto parse_error;
4018 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004019 if (done_word(&dest, &ctx)) {
4020 goto parse_error;
4021 }
4022 done_pipe(&ctx, PIPE_SEQ);
4023 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004024 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004025 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004026 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004027 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004028 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004029#if !BB_MMU
4030 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4031 if (pstring)
4032 *pstring = ctx.as_string.data;
4033 else
4034 o_free_unsafe(&ctx.as_string);
4035#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004036 debug_leave();
4037 debug_printf_parse("parse_stream return %p: "
4038 "end_trigger char found\n",
4039 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004040 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004041 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004042 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004043 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004044 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004045 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004046
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004047 /* Catch <, > before deciding whether this word is
4048 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4049 switch (ch) {
4050 case '>':
4051 redir_fd = redirect_opt_num(&dest);
4052 if (done_word(&dest, &ctx)) {
4053 goto parse_error;
4054 }
4055 redir_style = REDIRECT_OVERWRITE;
4056 if (next == '>') {
4057 redir_style = REDIRECT_APPEND;
4058 ch = i_getch(input);
4059 nommu_addchr(&ctx.as_string, ch);
4060 }
4061#if 0
4062 else if (next == '(') {
4063 syntax_error(">(process) not supported");
4064 goto parse_error;
4065 }
4066#endif
4067 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4068 goto parse_error;
4069 continue; /* back to top of while (1) */
4070 case '<':
4071 redir_fd = redirect_opt_num(&dest);
4072 if (done_word(&dest, &ctx)) {
4073 goto parse_error;
4074 }
4075 redir_style = REDIRECT_INPUT;
4076 if (next == '<') {
4077 redir_style = REDIRECT_HEREDOC;
4078 heredoc_cnt++;
4079 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4080 ch = i_getch(input);
4081 nommu_addchr(&ctx.as_string, ch);
4082 } else if (next == '>') {
4083 redir_style = REDIRECT_IO;
4084 ch = i_getch(input);
4085 nommu_addchr(&ctx.as_string, ch);
4086 }
4087#if 0
4088 else if (next == '(') {
4089 syntax_error("<(process) not supported");
4090 goto parse_error;
4091 }
4092#endif
4093 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4094 goto parse_error;
4095 continue; /* back to top of while (1) */
4096 }
4097
4098 if (dest.o_assignment == MAYBE_ASSIGNMENT
4099 /* check that we are not in word in "a=1 2>word b=1": */
4100 && !ctx.pending_redirect
4101 ) {
4102 /* ch is a special char and thus this word
4103 * cannot be an assignment */
4104 dest.o_assignment = NOT_ASSIGNMENT;
4105 }
4106
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004107 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4108
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004109 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00004110 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004111 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004112 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004113 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004114 if (ch == EOF || ch == '\n')
4115 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004116 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004117 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004118 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004119 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00004120 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004121 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004122 }
4123 break;
4124 case '\\':
4125 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004126 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004127 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004128 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004129 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004130 if (ch != '\n') {
4131 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004132 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004133 o_addchr(&dest, ch);
4134 nommu_addchr(&ctx.as_string, ch);
4135 /* Example: echo Hello \2>file
4136 * we need to know that word 2 is quoted */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004137 dest.has_quoted_part = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004138 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004139#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004140 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004141 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4142 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004143 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02004144#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004145 break;
4146 case '$':
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004147 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004148 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004149 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004150 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004151 }
Eric Andersen25f27032001-04-26 23:22:31 +00004152 break;
4153 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004154 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004155 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004156 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004157 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004158 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004159 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004160 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004161 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004162 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004163 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004164 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004165 }
Eric Andersen25f27032001-04-26 23:22:31 +00004166 break;
4167 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004168 dest.has_quoted_part = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004169 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004170 if (dest.o_assignment == NOT_ASSIGNMENT)
4171 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004172 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004173#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004174 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004175 unsigned pos;
4176
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004177 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4178 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004179 pos = dest.length;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004180 add_till_backquote(&dest, input);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004181# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004182 o_addstr(&ctx.as_string, dest.data + pos);
4183 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004184# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004185 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4186 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004187 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004188 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004189#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004190 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004191#if ENABLE_HUSH_CASE
4192 case_semi:
4193#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004194 if (done_word(&dest, &ctx)) {
4195 goto parse_error;
4196 }
4197 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004198#if ENABLE_HUSH_CASE
4199 /* Eat multiple semicolons, detect
4200 * whether it means something special */
4201 while (1) {
4202 ch = i_peek(input);
4203 if (ch != ';')
4204 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004205 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004206 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004207 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004208 ctx.ctx_dsemicolon = 1;
4209 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004210 break;
4211 }
4212 }
4213#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004214 new_cmd:
4215 /* We just finished a cmd. New one may start
4216 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004217 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004218 break;
4219 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004220 if (done_word(&dest, &ctx)) {
4221 goto parse_error;
4222 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004223 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004224 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004225 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004226 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004227 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004228 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004229 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004230 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004231 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004232 if (done_word(&dest, &ctx)) {
4233 goto parse_error;
4234 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004235#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004236 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004237 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004238#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004239 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004240 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004241 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004242 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004243 } else {
4244 /* we could pick up a file descriptor choice here
4245 * with redirect_opt_num(), but bash doesn't do it.
4246 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004247 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004248#if !BB_MMU
4249 o_reset_to_empty_unquoted(&ctx.as_string);
4250#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004251 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004252 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004253 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004254#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004255 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004256 if (ctx.ctx_res_w == RES_MATCH
4257 && ctx.command->argv == NULL /* not (word|(... */
4258 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004259 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004260 ) {
4261 continue;
4262 }
4263#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004264 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004265 if (parse_group(&dest, &ctx, input, ch) != 0) {
4266 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004267 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004268 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004269 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004270#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004271 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004272 goto case_semi;
4273#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004274 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004275 /* proper use of this character is caught by end_trigger:
4276 * if we see {, we call parse_group(..., end_trigger='}')
4277 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004278 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004279 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004280 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004281 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004282 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004283 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004284 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004285
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004286 parse_error:
4287 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004288 struct parse_context *pctx;
4289 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004290
4291 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004292 * Sample for finding leaks on syntax error recovery path.
4293 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004294 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004295 * Samples to catch leaks at execution:
4296 * while if (true | {true;}); then echo ok; fi; do break; done
4297 * 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 +00004298 */
4299 pctx = &ctx;
4300 do {
4301 /* Update pipe/command counts,
4302 * otherwise freeing may miss some */
4303 done_pipe(pctx, PIPE_SEQ);
4304 debug_printf_clean("freeing list %p from ctx %p\n",
4305 pctx->list_head, pctx);
4306 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004307 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004308 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004309#if !BB_MMU
4310 o_free_unsafe(&pctx->as_string);
4311#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004312 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004313 if (pctx != &ctx) {
4314 free(pctx);
4315 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004316 IF_HAS_KEYWORDS(pctx = p2;)
4317 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004318 /* Free text, clear all dest fields */
4319 o_free(&dest);
4320 /* If we are not in top-level parse, we return,
4321 * our caller will propagate error.
4322 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004323 if (end_trigger != ';') {
4324#if !BB_MMU
4325 if (pstring)
4326 *pstring = NULL;
4327#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004328 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004329 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004330 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004331 /* Discard cached input, force prompt */
4332 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004333 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004334 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004335 }
Eric Andersen25f27032001-04-26 23:22:31 +00004336}
4337
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004338
4339/*** Execution routines ***/
4340
4341/* Expansion can recurse, need forward decls: */
4342static char *expand_string_to_string(const char *str);
4343static int process_command_subs(o_string *dest, const char *s);
4344
4345/* expand_strvec_to_strvec() takes a list of strings, expands
4346 * all variable references within and returns a pointer to
4347 * a list of expanded strings, possibly with larger number
4348 * of strings. (Think VAR="a b"; echo $VAR).
4349 * This new list is allocated as a single malloc block.
4350 * NULL-terminated list of char* pointers is at the beginning of it,
4351 * followed by strings themself.
4352 * Caller can deallocate entire list by single free(list). */
4353
4354/* Store given string, finalizing the word and starting new one whenever
4355 * we encounter IFS char(s). This is used for expanding variable values.
4356 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4357static int expand_on_ifs(o_string *output, int n, const char *str)
4358{
4359 while (1) {
4360 int word_len = strcspn(str, G.ifs);
4361 if (word_len) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004362 if (output->o_escape)
4363 o_addqblock(output, str, word_len);
4364 else if (!output->o_glob)
4365 o_addblock(output, str, word_len);
4366 else /* if (!escape && glob) */ {
4367 /* Protect backslashes against globbing up :)
4368 * Example: "v='\*'; echo b$v"
4369 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004370 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004371 /*/ Why can't we do it easier? */
4372 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4373 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4374 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004375 str += word_len;
4376 }
4377 if (!*str) /* EOL - do not finalize word */
4378 break;
4379 o_addchr(output, '\0');
4380 debug_print_list("expand_on_ifs", output, n);
4381 n = o_save_ptr(output, n);
4382 str += strspn(str, G.ifs); /* skip ifs chars */
4383 }
4384 debug_print_list("expand_on_ifs[1]", output, n);
4385 return n;
4386}
4387
4388/* Helper to expand $((...)) and heredoc body. These act as if
4389 * they are in double quotes, with the exception that they are not :).
4390 * Just the rules are similar: "expand only $var and `cmd`"
4391 *
4392 * Returns malloced string.
4393 * As an optimization, we return NULL if expansion is not needed.
4394 */
4395static char *expand_pseudo_dquoted(const char *str)
4396{
4397 char *exp_str;
4398 struct in_str input;
4399 o_string dest = NULL_O_STRING;
4400
4401 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004402 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004403#if ENABLE_HUSH_TICK
4404 && !strchr(str, '`')
4405#endif
4406 ) {
4407 return NULL;
4408 }
4409
4410 /* We need to expand. Example:
4411 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4412 */
4413 setup_string_in_str(&input, str);
4414 parse_stream_dquoted(NULL, &dest, &input, EOF);
4415 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4416 exp_str = expand_string_to_string(dest.data);
4417 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4418 o_free_unsafe(&dest);
4419 return exp_str;
4420}
4421
4422#if ENABLE_SH_MATH_SUPPORT
4423static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
4424{
4425 arith_eval_hooks_t hooks;
4426 arith_t res;
4427 char *exp_str;
4428
4429 hooks.lookupvar = get_local_var_value;
4430 hooks.setvar = set_local_var_from_halves;
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02004431 //hooks.endofname = endofname;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004432 exp_str = expand_pseudo_dquoted(arg);
4433 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
4434 free(exp_str);
4435 return res;
4436}
4437#endif
4438
4439#if ENABLE_HUSH_BASH_COMPAT
4440/* ${var/[/]pattern[/repl]} helpers */
4441static char *strstr_pattern(char *val, const char *pattern, int *size)
4442{
4443 while (1) {
4444 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4445 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4446 if (end) {
4447 *size = end - val;
4448 return val;
4449 }
4450 if (*val == '\0')
4451 return NULL;
4452 /* Optimization: if "*pat" did not match the start of "string",
4453 * we know that "tring", "ring" etc will not match too:
4454 */
4455 if (pattern[0] == '*')
4456 return NULL;
4457 val++;
4458 }
4459}
4460static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4461{
4462 char *result = NULL;
4463 unsigned res_len = 0;
4464 unsigned repl_len = strlen(repl);
4465
4466 while (1) {
4467 int size;
4468 char *s = strstr_pattern(val, pattern, &size);
4469 if (!s)
4470 break;
4471
4472 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4473 memcpy(result + res_len, val, s - val);
4474 res_len += s - val;
4475 strcpy(result + res_len, repl);
4476 res_len += repl_len;
4477 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4478
4479 val = s + size;
4480 if (exp_op == '/')
4481 break;
4482 }
4483 if (val[0] && result) {
4484 result = xrealloc(result, res_len + strlen(val) + 1);
4485 strcpy(result + res_len, val);
4486 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4487 }
4488 debug_printf_varexp("result:'%s'\n", result);
4489 return result;
4490}
4491#endif
4492
4493/* Helper:
4494 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4495 */
4496static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp, char first_ch)
4497{
4498 const char *val = NULL;
4499 char *to_be_freed = NULL;
4500 char *p = *pp;
4501 char *var;
4502 char first_char;
4503 char exp_op;
4504 char exp_save = exp_save; /* for compiler */
4505 char *exp_saveptr; /* points to expansion operator */
4506 char *exp_word = exp_word; /* for compiler */
4507
4508 var = arg;
4509 *p = '\0';
4510 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4511 first_char = arg[0] = first_ch & 0x7f;
4512 exp_op = 0;
4513
4514 if (first_char == '#' && arg[1] && !exp_saveptr) {
4515 /* handle length expansion ${#var} */
4516 var++;
4517 exp_op = 'L';
4518 } else {
4519 /* maybe handle parameter expansion */
4520 if (exp_saveptr /* if 2nd char is one of expansion operators */
4521 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4522 ) {
4523 /* ${?:0}, ${#[:]%0} etc */
4524 exp_saveptr = var + 1;
4525 } else {
4526 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4527 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4528 }
4529 exp_op = exp_save = *exp_saveptr;
4530 if (exp_op) {
4531 exp_word = exp_saveptr + 1;
4532 if (exp_op == ':') {
4533 exp_op = *exp_word++;
4534 if (ENABLE_HUSH_BASH_COMPAT
4535 && (exp_op == '\0' || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4536 ) {
4537 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4538 exp_op = ':';
4539 exp_word--;
4540 }
4541 }
4542 *exp_saveptr = '\0';
4543 } /* else: it's not an expansion op, but bare ${var} */
4544 }
4545
4546 /* lookup the variable in question */
4547 if (isdigit(var[0])) {
4548 /* parse_dollar() should have vetted var for us */
4549 int n = xatoi_positive(var);
4550 if (n < G.global_argc)
4551 val = G.global_argv[n];
4552 /* else val remains NULL: $N with too big N */
4553 } else {
4554 switch (var[0]) {
4555 case '$': /* pid */
4556 val = utoa(G.root_pid);
4557 break;
4558 case '!': /* bg pid */
4559 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4560 break;
4561 case '?': /* exitcode */
4562 val = utoa(G.last_exitcode);
4563 break;
4564 case '#': /* argc */
4565 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4566 break;
4567 default:
4568 val = get_local_var_value(var);
4569 }
4570 }
4571
4572 /* Handle any expansions */
4573 if (exp_op == 'L') {
4574 debug_printf_expand("expand: length(%s)=", val);
4575 val = utoa(val ? strlen(val) : 0);
4576 debug_printf_expand("%s\n", val);
4577 } else if (exp_op) {
4578 if (exp_op == '%' || exp_op == '#') {
4579 /* Standard-mandated substring removal ops:
4580 * ${parameter%word} - remove smallest suffix pattern
4581 * ${parameter%%word} - remove largest suffix pattern
4582 * ${parameter#word} - remove smallest prefix pattern
4583 * ${parameter##word} - remove largest prefix pattern
4584 *
4585 * Word is expanded to produce a glob pattern.
4586 * Then var's value is matched to it and matching part removed.
4587 */
4588 if (val && val[0]) {
4589 char *exp_exp_word;
4590 char *loc;
4591 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4592 if (exp_op == *exp_word) /* ## or %% */
4593 exp_word++;
4594//TODO: avoid xstrdup unless needed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004595// (see HACK ALERT below for an example)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004596 val = to_be_freed = xstrdup(val);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004597//TODO: fix expansion rules:
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004598 exp_exp_word = expand_pseudo_dquoted(exp_word);
4599 if (exp_exp_word)
4600 exp_word = exp_exp_word;
4601 loc = scan_and_match(to_be_freed, exp_word, scan_flags);
4602 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4603 // exp_op, to_be_freed, exp_word, loc);
4604 free(exp_exp_word);
4605 if (loc) { /* match was found */
4606 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4607 val = loc;
4608 else /* %[%] */
4609 *loc = '\0';
4610 }
4611 }
4612 }
4613#if ENABLE_HUSH_BASH_COMPAT
4614 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004615 /* It's ${var/[/]pattern[/repl]} thing.
4616 * Note that in encoded form it has TWO parts:
4617 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4618 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004619 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004620 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004621 if (val && val[0]) {
4622 /* It's ${var/[/]pattern[/repl]} thing */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004623 /*
4624 * Pattern is taken literally, while
4625 * repl should be de-backslased and globbed
4626 * by the usual expansion rules:
4627 * >az; >bz;
4628 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4629 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4630 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4631 * v='a bz'; echo ${v/a*z/\z} prints "z"
4632 * (note that a*z _pattern_ is never globbed!)
4633 */
4634//TODO: fix expansion rules:
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004635 char *pattern, *repl, *t;
4636 pattern = expand_pseudo_dquoted(exp_word);
4637 if (!pattern)
4638 pattern = xstrdup(exp_word);
4639 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4640 *p++ = SPECIAL_VAR_SYMBOL;
4641 exp_word = p;
4642 p = strchr(p, SPECIAL_VAR_SYMBOL);
4643 *p = '\0';
4644 repl = expand_pseudo_dquoted(exp_word);
4645 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4646 /* HACK ALERT. We depend here on the fact that
4647 * G.global_argv and results of utoa and get_local_var_value
4648 * are actually in writable memory:
4649 * replace_pattern momentarily stores NULs there. */
4650 t = (char*)val;
4651 to_be_freed = replace_pattern(t,
4652 pattern,
4653 (repl ? repl : exp_word),
4654 exp_op);
4655 if (to_be_freed) /* at least one replace happened */
4656 val = to_be_freed;
4657 free(pattern);
4658 free(repl);
4659 }
4660 }
4661#endif
4662 else if (exp_op == ':') {
4663#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4664 /* It's ${var:N[:M]} bashism.
4665 * Note that in encoded form it has TWO parts:
4666 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4667 */
4668 arith_t beg, len;
4669 int errcode = 0;
4670
4671 beg = expand_and_evaluate_arith(exp_word, &errcode);
4672 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4673 *p++ = SPECIAL_VAR_SYMBOL;
4674 exp_word = p;
4675 p = strchr(p, SPECIAL_VAR_SYMBOL);
4676 *p = '\0';
4677 len = expand_and_evaluate_arith(exp_word, &errcode);
4678 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4679
4680 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
4681 if (beg < 0) /* bash compat */
4682 beg = 0;
4683 debug_printf_varexp("from val:'%s'\n", val);
4684 if (len == 0 || !val || beg >= strlen(val))
4685 val = "";
4686 else {
4687 /* Paranoia. What if user entered 9999999999999
4688 * which fits in arith_t but not int? */
4689 if (len >= INT_MAX)
4690 len = INT_MAX;
4691 val = to_be_freed = xstrndup(val + beg, len);
4692 }
4693 debug_printf_varexp("val:'%s'\n", val);
4694 } else
4695#endif
4696 {
4697 die_if_script("malformed ${%s:...}", var);
4698 val = "";
4699 }
4700 } else { /* one of "-=+?" */
4701 /* Standard-mandated substitution ops:
4702 * ${var?word} - indicate error if unset
4703 * If var is unset, word (or a message indicating it is unset
4704 * if word is null) is written to standard error
4705 * and the shell exits with a non-zero exit status.
4706 * Otherwise, the value of var is substituted.
4707 * ${var-word} - use default value
4708 * If var is unset, word is substituted.
4709 * ${var=word} - assign and use default value
4710 * If var is unset, word is assigned to var.
4711 * In all cases, final value of var is substituted.
4712 * ${var+word} - use alternative value
4713 * If var is unset, null is substituted.
4714 * Otherwise, word is substituted.
4715 *
4716 * Word is subjected to tilde expansion, parameter expansion,
4717 * command substitution, and arithmetic expansion.
4718 * If word is not needed, it is not expanded.
4719 *
4720 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4721 * but also treat null var as if it is unset.
4722 */
4723 int use_word = (!val || ((exp_save == ':') && !val[0]));
4724 if (exp_op == '+')
4725 use_word = !use_word;
4726 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4727 (exp_save == ':') ? "true" : "false", use_word);
4728 if (use_word) {
4729 to_be_freed = expand_pseudo_dquoted(exp_word);
4730 if (to_be_freed)
4731 exp_word = to_be_freed;
4732 if (exp_op == '?') {
4733 /* mimic bash message */
4734 die_if_script("%s: %s",
4735 var,
4736 exp_word[0] ? exp_word : "parameter null or not set"
4737 );
4738//TODO: how interactive bash aborts expansion mid-command?
4739 } else {
4740 val = exp_word;
4741 }
4742
4743 if (exp_op == '=') {
4744 /* ${var=[word]} or ${var:=[word]} */
4745 if (isdigit(var[0]) || var[0] == '#') {
4746 /* mimic bash message */
4747 die_if_script("$%s: cannot assign in this way", var);
4748 val = NULL;
4749 } else {
4750 char *new_var = xasprintf("%s=%s", var, val);
4751 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4752 }
4753 }
4754 }
4755 } /* one of "-=+?" */
4756
4757 *exp_saveptr = exp_save;
4758 } /* if (exp_op) */
4759
4760 arg[0] = first_ch;
4761
4762 *pp = p;
4763 *to_be_freed_pp = to_be_freed;
4764 return val;
4765}
4766
4767/* Expand all variable references in given string, adding words to list[]
4768 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4769 * to be filled). This routine is extremely tricky: has to deal with
4770 * variables/parameters with whitespace, $* and $@, and constructs like
4771 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4772static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
4773{
4774 /* or_mask is either 0 (normal case) or 0x80 -
4775 * expansion of right-hand side of assignment == 1-element expand.
4776 * It will also do no globbing, and thus we must not backslash-quote!
4777 */
4778 char ored_ch;
4779 char *p;
4780
4781 ored_ch = 0;
4782
4783 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
4784 debug_print_list("expand_vars_to_list", output, n);
4785 n = o_save_ptr(output, n);
4786 debug_print_list("expand_vars_to_list[0]", output, n);
4787
4788 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4789 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004790 char *to_be_freed = NULL;
4791 const char *val = NULL;
4792#if ENABLE_HUSH_TICK
4793 o_string subst_result = NULL_O_STRING;
4794#endif
4795#if ENABLE_SH_MATH_SUPPORT
4796 char arith_buf[sizeof(arith_t)*3 + 2];
4797#endif
4798 o_addblock(output, arg, p - arg);
4799 debug_print_list("expand_vars_to_list[1]", output, n);
4800 arg = ++p;
4801 p = strchr(p, SPECIAL_VAR_SYMBOL);
4802
4803 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
4804 /* "$@" is special. Even if quoted, it can still
4805 * expand to nothing (not even an empty string) */
4806 if ((first_ch & 0x7f) != '@')
4807 ored_ch |= first_ch;
4808
4809 switch (first_ch & 0x7f) {
4810 /* Highest bit in first_ch indicates that var is double-quoted */
4811 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004812 case '@': {
4813 int i;
4814 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004815 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004816 i = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004817 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4818 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4819 smallint sv = output->o_escape;
4820 /* unquoted var's contents should be globbed, so don't escape */
4821 output->o_escape = 0;
4822 while (G.global_argv[i]) {
4823 n = expand_on_ifs(output, n, G.global_argv[i]);
4824 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4825 if (G.global_argv[i++][0] && G.global_argv[i]) {
4826 /* this argv[] is not empty and not last:
4827 * put terminating NUL, start new word */
4828 o_addchr(output, '\0');
4829 debug_print_list("expand_vars_to_list[2]", output, n);
4830 n = o_save_ptr(output, n);
4831 debug_print_list("expand_vars_to_list[3]", output, n);
4832 }
4833 }
4834 output->o_escape = sv;
4835 } else
4836 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
4837 * and in this case should treat it like '$*' - see 'else...' below */
4838 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
4839 while (1) {
4840 o_addQstr(output, G.global_argv[i]);
4841 if (++i >= G.global_argc)
4842 break;
4843 o_addchr(output, '\0');
4844 debug_print_list("expand_vars_to_list[4]", output, n);
4845 n = o_save_ptr(output, n);
4846 }
4847 } else { /* quoted $*: add as one word */
4848 while (1) {
4849 o_addQstr(output, G.global_argv[i]);
4850 if (!G.global_argv[++i])
4851 break;
4852 if (G.ifs[0])
4853 o_addchr(output, G.ifs[0]);
4854 }
4855 }
4856 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004857 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004858 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4859 /* "Empty variable", used to make "" etc to not disappear */
4860 arg++;
4861 ored_ch = 0x80;
4862 break;
4863#if ENABLE_HUSH_TICK
4864 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4865 *p = '\0';
4866 arg++;
4867 /* Can't just stuff it into output o_string,
4868 * expanded result may need to be globbed
4869 * and $IFS-splitted */
4870 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4871 G.last_exitcode = process_command_subs(&subst_result, arg);
4872 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4873 val = subst_result.data;
4874 goto store_val;
4875#endif
4876#if ENABLE_SH_MATH_SUPPORT
4877 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4878 arith_t res;
4879 int errcode;
4880
4881 arg++; /* skip '+' */
4882 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4883 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4884 res = expand_and_evaluate_arith(arg, &errcode);
4885
4886 if (errcode < 0) {
4887 const char *msg = "error in arithmetic";
4888 switch (errcode) {
4889 case -3:
4890 msg = "exponent less than 0";
4891 break;
4892 case -2:
4893 msg = "divide by 0";
4894 break;
4895 case -5:
4896 msg = "expression recursion loop detected";
4897 break;
4898 }
4899 die_if_script(msg);
4900 }
4901 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
4902 sprintf(arith_buf, arith_t_fmt, res);
4903 val = arith_buf;
4904 break;
4905 }
4906#endif
4907 default:
4908 val = expand_one_var(&to_be_freed, arg, &p, first_ch);
4909 IF_HUSH_TICK(store_val:)
4910 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4911 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
4912 if (val && val[0]) {
4913 /* unquoted var's contents should be globbed, so don't escape */
4914 smallint sv = output->o_escape;
4915 output->o_escape = 0;
4916 n = expand_on_ifs(output, n, val);
4917 val = NULL;
4918 output->o_escape = sv;
4919 }
4920 } else { /* quoted $VAR, val will be appended below */
4921 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
4922 }
4923 break;
4924
4925 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4926
4927 if (val && val[0]) {
4928 o_addQstr(output, val);
4929 }
4930 free(to_be_freed);
4931 /* Do the check to avoid writing to a const string */
4932 if (*p != SPECIAL_VAR_SYMBOL)
4933 *p = SPECIAL_VAR_SYMBOL;
4934
4935#if ENABLE_HUSH_TICK
4936 o_free(&subst_result);
4937#endif
4938 arg = ++p;
4939 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4940
4941 if (arg[0]) {
4942 debug_print_list("expand_vars_to_list[a]", output, n);
4943 /* this part is literal, and it was already pre-quoted
4944 * if needed (much earlier), do not use o_addQstr here! */
4945 o_addstr_with_NUL(output, arg);
4946 debug_print_list("expand_vars_to_list[b]", output, n);
4947 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
4948 && !(ored_ch & 0x80) /* and all vars were not quoted. */
4949 ) {
4950 n--;
4951 /* allow to reuse list[n] later without re-growth */
4952 output->has_empty_slot = 1;
4953 } else {
4954 o_addchr(output, '\0');
4955 }
4956
4957 return n;
4958}
4959
4960enum {
4961 EXPVAR_FLAG_GLOB = 0x200,
4962 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
4963 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
4964};
4965static char **expand_variables(char **argv, unsigned or_mask)
4966{
4967 int n;
4968 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004969 o_string output = NULL_O_STRING;
4970
4971 /* protect against globbing for "$var"? */
4972 /* (unquoted $var will temporarily switch it off) */
4973 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
4974 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
4975
4976 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02004977 while (*argv) {
4978 n = expand_vars_to_list(&output, n, *argv, (unsigned char)or_mask);
4979 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004980 }
4981 debug_print_list("expand_variables", &output, n);
4982
4983 /* output.data (malloced in one block) gets returned in "list" */
4984 list = o_finalize_list(&output, n);
4985 debug_print_strings("expand_variables[1]", list);
4986 return list;
4987}
4988
4989static char **expand_strvec_to_strvec(char **argv)
4990{
4991 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
4992}
4993
4994#if ENABLE_HUSH_BASH_COMPAT
4995static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
4996{
4997 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
4998}
4999#endif
5000
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005001/* Used for expansion of right hand of assignments */
5002/* NB: should NOT do globbing!
5003 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
5004static char *expand_string_to_string(const char *str)
5005{
5006 char *argv[2], **list;
5007
5008 /* This is generally an optimization, but it also
5009 * handles "", which otherwise trips over !list[0] check below.
5010 * (is this ever happens that we actually get str="" here?)
5011 */
5012 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5013 //TODO: Can use on strings with \ too, just unbackslash() them?
5014 debug_printf_expand("string_to_string(fast)='%s'\n", str);
5015 return xstrdup(str);
5016 }
5017
5018 argv[0] = (char*)str;
5019 argv[1] = NULL;
5020 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
5021 if (HUSH_DEBUG)
5022 if (!list[0] || list[1])
5023 bb_error_msg_and_die("BUG in varexp2");
5024 /* actually, just move string 2*sizeof(char*) bytes back */
5025 overlapping_strcpy((char*)list, list[0]);
5026 unbackslash((char*)list);
5027 debug_printf_expand("string_to_string='%s'\n", (char*)list);
5028 return (char*)list;
5029}
5030
5031/* Used for "eval" builtin */
5032static char* expand_strvec_to_string(char **argv)
5033{
5034 char **list;
5035
5036 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
5037 /* Convert all NULs to spaces */
5038 if (list[0]) {
5039 int n = 1;
5040 while (list[n]) {
5041 if (HUSH_DEBUG)
5042 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5043 bb_error_msg_and_die("BUG in varexp3");
5044 /* bash uses ' ' regardless of $IFS contents */
5045 list[n][-1] = ' ';
5046 n++;
5047 }
5048 }
5049 overlapping_strcpy((char*)list, list[0]);
5050 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5051 return (char*)list;
5052}
5053
5054static char **expand_assignments(char **argv, int count)
5055{
5056 int i;
5057 char **p;
5058
5059 G.expanded_assignments = p = NULL;
5060 /* Expand assignments into one string each */
5061 for (i = 0; i < count; i++) {
5062 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
5063 }
5064 G.expanded_assignments = NULL;
5065 return p;
5066}
5067
5068
5069#if BB_MMU
5070/* never called */
5071void re_execute_shell(char ***to_free, const char *s,
5072 char *g_argv0, char **g_argv,
5073 char **builtin_argv) NORETURN;
5074
5075static void reset_traps_to_defaults(void)
5076{
5077 /* This function is always called in a child shell
5078 * after fork (not vfork, NOMMU doesn't use this function).
5079 */
5080 unsigned sig;
5081 unsigned mask;
5082
5083 /* Child shells are not interactive.
5084 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5085 * Testcase: (while :; do :; done) + ^Z should background.
5086 * Same goes for SIGTERM, SIGHUP, SIGINT.
5087 */
5088 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5089 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5090
5091 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5092 * Stupid. It can be done with *single* &= op, but we can't use
5093 * the fact that G.blocked_set is implemented as a bitmask
5094 * in libc... */
5095 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5096 sig = 1;
5097 while (1) {
5098 if (mask & 1) {
5099 /* Careful. Only if no trap or trap is not "" */
5100 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5101 sigdelset(&G.blocked_set, sig);
5102 }
5103 mask >>= 1;
5104 if (!mask)
5105 break;
5106 sig++;
5107 }
5108 /* Our homegrown sig mask is saner to work with :) */
5109 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5110
5111 /* Resetting all traps to default except empty ones */
5112 mask = G.non_DFL_mask;
5113 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5114 if (!G.traps[sig] || !G.traps[sig][0])
5115 continue;
5116 free(G.traps[sig]);
5117 G.traps[sig] = NULL;
5118 /* There is no signal for 0 (EXIT) */
5119 if (sig == 0)
5120 continue;
5121 /* There was a trap handler, we just removed it.
5122 * But if sig still has non-DFL handling,
5123 * we should not unblock the sig. */
5124 if (mask & 1)
5125 continue;
5126 sigdelset(&G.blocked_set, sig);
5127 }
5128 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5129}
5130
5131#else /* !BB_MMU */
5132
5133static void re_execute_shell(char ***to_free, const char *s,
5134 char *g_argv0, char **g_argv,
5135 char **builtin_argv) NORETURN;
5136static void re_execute_shell(char ***to_free, const char *s,
5137 char *g_argv0, char **g_argv,
5138 char **builtin_argv)
5139{
5140# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5141 /* delims + 2 * (number of bytes in printed hex numbers) */
5142 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5143 char *heredoc_argv[4];
5144 struct variable *cur;
5145# if ENABLE_HUSH_FUNCTIONS
5146 struct function *funcp;
5147# endif
5148 char **argv, **pp;
5149 unsigned cnt;
5150 unsigned long long empty_trap_mask;
5151
5152 if (!g_argv0) { /* heredoc */
5153 argv = heredoc_argv;
5154 argv[0] = (char *) G.argv0_for_re_execing;
5155 argv[1] = (char *) "-<";
5156 argv[2] = (char *) s;
5157 argv[3] = NULL;
5158 pp = &argv[3]; /* used as pointer to empty environment */
5159 goto do_exec;
5160 }
5161
5162 cnt = 0;
5163 pp = builtin_argv;
5164 if (pp) while (*pp++)
5165 cnt++;
5166
5167 empty_trap_mask = 0;
5168 if (G.traps) {
5169 int sig;
5170 for (sig = 1; sig < NSIG; sig++) {
5171 if (G.traps[sig] && !G.traps[sig][0])
5172 empty_trap_mask |= 1LL << sig;
5173 }
5174 }
5175
5176 sprintf(param_buf, NOMMU_HACK_FMT
5177 , (unsigned) G.root_pid
5178 , (unsigned) G.root_ppid
5179 , (unsigned) G.last_bg_pid
5180 , (unsigned) G.last_exitcode
5181 , cnt
5182 , empty_trap_mask
5183 IF_HUSH_LOOPS(, G.depth_of_loop)
5184 );
5185# undef NOMMU_HACK_FMT
5186 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5187 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5188 */
5189 cnt += 6;
5190 for (cur = G.top_var; cur; cur = cur->next) {
5191 if (!cur->flg_export || cur->flg_read_only)
5192 cnt += 2;
5193 }
5194# if ENABLE_HUSH_FUNCTIONS
5195 for (funcp = G.top_func; funcp; funcp = funcp->next)
5196 cnt += 3;
5197# endif
5198 pp = g_argv;
5199 while (*pp++)
5200 cnt++;
5201 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5202 *pp++ = (char *) G.argv0_for_re_execing;
5203 *pp++ = param_buf;
5204 for (cur = G.top_var; cur; cur = cur->next) {
5205 if (strcmp(cur->varstr, hush_version_str) == 0)
5206 continue;
5207 if (cur->flg_read_only) {
5208 *pp++ = (char *) "-R";
5209 *pp++ = cur->varstr;
5210 } else if (!cur->flg_export) {
5211 *pp++ = (char *) "-V";
5212 *pp++ = cur->varstr;
5213 }
5214 }
5215# if ENABLE_HUSH_FUNCTIONS
5216 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5217 *pp++ = (char *) "-F";
5218 *pp++ = funcp->name;
5219 *pp++ = funcp->body_as_string;
5220 }
5221# endif
5222 /* We can pass activated traps here. Say, -Tnn:trap_string
5223 *
5224 * However, POSIX says that subshells reset signals with traps
5225 * to SIG_DFL.
5226 * I tested bash-3.2 and it not only does that with true subshells
5227 * of the form ( list ), but with any forked children shells.
5228 * I set trap "echo W" WINCH; and then tried:
5229 *
5230 * { echo 1; sleep 20; echo 2; } &
5231 * while true; do echo 1; sleep 20; echo 2; break; done &
5232 * true | { echo 1; sleep 20; echo 2; } | cat
5233 *
5234 * In all these cases sending SIGWINCH to the child shell
5235 * did not run the trap. If I add trap "echo V" WINCH;
5236 * _inside_ group (just before echo 1), it works.
5237 *
5238 * I conclude it means we don't need to pass active traps here.
5239 * Even if we would use signal handlers instead of signal masking
5240 * in order to implement trap handling,
5241 * exec syscall below resets signals to SIG_DFL for us.
5242 */
5243 *pp++ = (char *) "-c";
5244 *pp++ = (char *) s;
5245 if (builtin_argv) {
5246 while (*++builtin_argv)
5247 *pp++ = *builtin_argv;
5248 *pp++ = (char *) "";
5249 }
5250 *pp++ = g_argv0;
5251 while (*g_argv)
5252 *pp++ = *g_argv++;
5253 /* *pp = NULL; - is already there */
5254 pp = environ;
5255
5256 do_exec:
5257 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5258 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5259 execve(bb_busybox_exec_path, argv, pp);
5260 /* Fallback. Useful for init=/bin/hush usage etc */
5261 if (argv[0][0] == '/')
5262 execve(argv[0], argv, pp);
5263 xfunc_error_retval = 127;
5264 bb_error_msg_and_die("can't re-execute the shell");
5265}
5266#endif /* !BB_MMU */
5267
5268
5269static int run_and_free_list(struct pipe *pi);
5270
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005271/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005272 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5273 * end_trigger controls how often we stop parsing
5274 * NUL: parse all, execute, return
5275 * ';': parse till ';' or newline, execute, repeat till EOF
5276 */
5277static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005278{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005279 /* Why we need empty flag?
5280 * An obscure corner case "false; ``; echo $?":
5281 * empty command in `` should still set $? to 0.
5282 * But we can't just set $? to 0 at the start,
5283 * this breaks "false; echo `echo $?`" case.
5284 */
5285 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005286 while (1) {
5287 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005288
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005289 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005290 if (!pipe_list) { /* EOF */
5291 if (empty)
5292 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005293 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005294 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005295 debug_print_tree(pipe_list, 0);
5296 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5297 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005298 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005299 }
Eric Andersen25f27032001-04-26 23:22:31 +00005300}
5301
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005302static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005303{
5304 struct in_str input;
5305 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005306 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005307}
5308
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005309static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005310{
Eric Andersen25f27032001-04-26 23:22:31 +00005311 struct in_str input;
5312 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005313 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005314}
5315
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005316#if ENABLE_HUSH_TICK
5317static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5318{
5319 pid_t pid;
5320 int channel[2];
5321# if !BB_MMU
5322 char **to_free = NULL;
5323# endif
5324
5325 xpipe(channel);
5326 pid = BB_MMU ? xfork() : xvfork();
5327 if (pid == 0) { /* child */
5328 disable_restore_tty_pgrp_on_exit();
5329 /* Process substitution is not considered to be usual
5330 * 'command execution'.
5331 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5332 */
5333 bb_signals(0
5334 + (1 << SIGTSTP)
5335 + (1 << SIGTTIN)
5336 + (1 << SIGTTOU)
5337 , SIG_IGN);
5338 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5339 close(channel[0]); /* NB: close _first_, then move fd! */
5340 xmove_fd(channel[1], 1);
5341 /* Prevent it from trying to handle ctrl-z etc */
5342 IF_HUSH_JOB(G.run_list_level = 1;)
5343 /* Awful hack for `trap` or $(trap).
5344 *
5345 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5346 * contains an example where "trap" is executed in a subshell:
5347 *
5348 * save_traps=$(trap)
5349 * ...
5350 * eval "$save_traps"
5351 *
5352 * Standard does not say that "trap" in subshell shall print
5353 * parent shell's traps. It only says that its output
5354 * must have suitable form, but then, in the above example
5355 * (which is not supposed to be normative), it implies that.
5356 *
5357 * bash (and probably other shell) does implement it
5358 * (traps are reset to defaults, but "trap" still shows them),
5359 * but as a result, "trap" logic is hopelessly messed up:
5360 *
5361 * # trap
5362 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5363 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5364 * # true | trap <--- trap is in subshell - no output (ditto)
5365 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5366 * trap -- 'echo Ho' SIGWINCH
5367 * # echo `(trap)` <--- in subshell in subshell - output
5368 * trap -- 'echo Ho' SIGWINCH
5369 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5370 * trap -- 'echo Ho' SIGWINCH
5371 *
5372 * The rules when to forget and when to not forget traps
5373 * get really complex and nonsensical.
5374 *
5375 * Our solution: ONLY bare $(trap) or `trap` is special.
5376 */
5377 s = skip_whitespace(s);
5378 if (strncmp(s, "trap", 4) == 0
5379 && skip_whitespace(s + 4)[0] == '\0'
5380 ) {
5381 static const char *const argv[] = { NULL, NULL };
5382 builtin_trap((char**)argv);
5383 exit(0); /* not _exit() - we need to fflush */
5384 }
5385# if BB_MMU
5386 reset_traps_to_defaults();
5387 parse_and_run_string(s);
5388 _exit(G.last_exitcode);
5389# else
5390 /* We re-execute after vfork on NOMMU. This makes this script safe:
5391 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5392 * huge=`cat BIG` # was blocking here forever
5393 * echo OK
5394 */
5395 re_execute_shell(&to_free,
5396 s,
5397 G.global_argv[0],
5398 G.global_argv + 1,
5399 NULL);
5400# endif
5401 }
5402
5403 /* parent */
5404 *pid_p = pid;
5405# if ENABLE_HUSH_FAST
5406 G.count_SIGCHLD++;
5407//bb_error_msg("[%d] fork in generate_stream_from_string:"
5408// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5409// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5410# endif
5411 enable_restore_tty_pgrp_on_exit();
5412# if !BB_MMU
5413 free(to_free);
5414# endif
5415 close(channel[1]);
5416 close_on_exec_on(channel[0]);
5417 return xfdopen_for_read(channel[0]);
5418}
5419
5420/* Return code is exit status of the process that is run. */
5421static int process_command_subs(o_string *dest, const char *s)
5422{
5423 FILE *fp;
5424 struct in_str pipe_str;
5425 pid_t pid;
5426 int status, ch, eol_cnt;
5427
5428 fp = generate_stream_from_string(s, &pid);
5429
5430 /* Now send results of command back into original context */
5431 setup_file_in_str(&pipe_str, fp);
5432 eol_cnt = 0;
5433 while ((ch = i_getch(&pipe_str)) != EOF) {
5434 if (ch == '\n') {
5435 eol_cnt++;
5436 continue;
5437 }
5438 while (eol_cnt) {
5439 o_addchr(dest, '\n');
5440 eol_cnt--;
5441 }
5442 o_addQchr(dest, ch);
5443 }
5444
5445 debug_printf("done reading from `cmd` pipe, closing it\n");
5446 fclose(fp);
5447 /* We need to extract exitcode. Test case
5448 * "true; echo `sleep 1; false` $?"
5449 * should print 1 */
5450 safe_waitpid(pid, &status, 0);
5451 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5452 return WEXITSTATUS(status);
5453}
5454#endif /* ENABLE_HUSH_TICK */
5455
5456
5457static void setup_heredoc(struct redir_struct *redir)
5458{
5459 struct fd_pair pair;
5460 pid_t pid;
5461 int len, written;
5462 /* the _body_ of heredoc (misleading field name) */
5463 const char *heredoc = redir->rd_filename;
5464 char *expanded;
5465#if !BB_MMU
5466 char **to_free;
5467#endif
5468
5469 expanded = NULL;
5470 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5471 expanded = expand_pseudo_dquoted(heredoc);
5472 if (expanded)
5473 heredoc = expanded;
5474 }
5475 len = strlen(heredoc);
5476
5477 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5478 xpiped_pair(pair);
5479 xmove_fd(pair.rd, redir->rd_fd);
5480
5481 /* Try writing without forking. Newer kernels have
5482 * dynamically growing pipes. Must use non-blocking write! */
5483 ndelay_on(pair.wr);
5484 while (1) {
5485 written = write(pair.wr, heredoc, len);
5486 if (written <= 0)
5487 break;
5488 len -= written;
5489 if (len == 0) {
5490 close(pair.wr);
5491 free(expanded);
5492 return;
5493 }
5494 heredoc += written;
5495 }
5496 ndelay_off(pair.wr);
5497
5498 /* Okay, pipe buffer was not big enough */
5499 /* Note: we must not create a stray child (bastard? :)
5500 * for the unsuspecting parent process. Child creates a grandchild
5501 * and exits before parent execs the process which consumes heredoc
5502 * (that exec happens after we return from this function) */
5503#if !BB_MMU
5504 to_free = NULL;
5505#endif
5506 pid = xvfork();
5507 if (pid == 0) {
5508 /* child */
5509 disable_restore_tty_pgrp_on_exit();
5510 pid = BB_MMU ? xfork() : xvfork();
5511 if (pid != 0)
5512 _exit(0);
5513 /* grandchild */
5514 close(redir->rd_fd); /* read side of the pipe */
5515#if BB_MMU
5516 full_write(pair.wr, heredoc, len); /* may loop or block */
5517 _exit(0);
5518#else
5519 /* Delegate blocking writes to another process */
5520 xmove_fd(pair.wr, STDOUT_FILENO);
5521 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5522#endif
5523 }
5524 /* parent */
5525#if ENABLE_HUSH_FAST
5526 G.count_SIGCHLD++;
5527//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5528#endif
5529 enable_restore_tty_pgrp_on_exit();
5530#if !BB_MMU
5531 free(to_free);
5532#endif
5533 close(pair.wr);
5534 free(expanded);
5535 wait(NULL); /* wait till child has died */
5536}
5537
5538/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5539 * and stderr if they are redirected. */
5540static int setup_redirects(struct command *prog, int squirrel[])
5541{
5542 int openfd, mode;
5543 struct redir_struct *redir;
5544
5545 for (redir = prog->redirects; redir; redir = redir->next) {
5546 if (redir->rd_type == REDIRECT_HEREDOC2) {
5547 /* rd_fd<<HERE case */
5548 if (squirrel && redir->rd_fd < 3
5549 && squirrel[redir->rd_fd] < 0
5550 ) {
5551 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5552 }
5553 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5554 * of the heredoc */
5555 debug_printf_parse("set heredoc '%s'\n",
5556 redir->rd_filename);
5557 setup_heredoc(redir);
5558 continue;
5559 }
5560
5561 if (redir->rd_dup == REDIRFD_TO_FILE) {
5562 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5563 char *p;
5564 if (redir->rd_filename == NULL) {
5565 /* Something went wrong in the parse.
5566 * Pretend it didn't happen */
5567 bb_error_msg("bug in redirect parse");
5568 continue;
5569 }
5570 mode = redir_table[redir->rd_type].mode;
5571 p = expand_string_to_string(redir->rd_filename);
5572 openfd = open_or_warn(p, mode);
5573 free(p);
5574 if (openfd < 0) {
5575 /* this could get lost if stderr has been redirected, but
5576 * bash and ash both lose it as well (though zsh doesn't!) */
5577//what the above comment tries to say?
5578 return 1;
5579 }
5580 } else {
5581 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5582 openfd = redir->rd_dup;
5583 }
5584
5585 if (openfd != redir->rd_fd) {
5586 if (squirrel && redir->rd_fd < 3
5587 && squirrel[redir->rd_fd] < 0
5588 ) {
5589 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5590 }
5591 if (openfd == REDIRFD_CLOSE) {
5592 /* "n>-" means "close me" */
5593 close(redir->rd_fd);
5594 } else {
5595 xdup2(openfd, redir->rd_fd);
5596 if (redir->rd_dup == REDIRFD_TO_FILE)
5597 close(openfd);
5598 }
5599 }
5600 }
5601 return 0;
5602}
5603
5604static void restore_redirects(int squirrel[])
5605{
5606 int i, fd;
5607 for (i = 0; i < 3; i++) {
5608 fd = squirrel[i];
5609 if (fd != -1) {
5610 /* We simply die on error */
5611 xmove_fd(fd, i);
5612 }
5613 }
5614}
5615
5616static char *find_in_path(const char *arg)
5617{
5618 char *ret = NULL;
5619 const char *PATH = get_local_var_value("PATH");
5620
5621 if (!PATH)
5622 return NULL;
5623
5624 while (1) {
5625 const char *end = strchrnul(PATH, ':');
5626 int sz = end - PATH; /* must be int! */
5627
5628 free(ret);
5629 if (sz != 0) {
5630 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5631 } else {
5632 /* We have xxx::yyyy in $PATH,
5633 * it means "use current dir" */
5634 ret = xstrdup(arg);
5635 }
5636 if (access(ret, F_OK) == 0)
5637 break;
5638
5639 if (*end == '\0') {
5640 free(ret);
5641 return NULL;
5642 }
5643 PATH = end + 1;
5644 }
5645
5646 return ret;
5647}
5648
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005649static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005650 const struct built_in_command *x,
5651 const struct built_in_command *end)
5652{
5653 while (x != end) {
5654 if (strcmp(name, x->b_cmd) != 0) {
5655 x++;
5656 continue;
5657 }
5658 debug_printf_exec("found builtin '%s'\n", name);
5659 return x;
5660 }
5661 return NULL;
5662}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005663static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005664{
5665 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5666}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005667static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005668{
5669 const struct built_in_command *x = find_builtin1(name);
5670 if (x)
5671 return x;
5672 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5673}
5674
5675#if ENABLE_HUSH_FUNCTIONS
5676static struct function **find_function_slot(const char *name)
5677{
5678 struct function **funcpp = &G.top_func;
5679 while (*funcpp) {
5680 if (strcmp(name, (*funcpp)->name) == 0) {
5681 break;
5682 }
5683 funcpp = &(*funcpp)->next;
5684 }
5685 return funcpp;
5686}
5687
5688static const struct function *find_function(const char *name)
5689{
5690 const struct function *funcp = *find_function_slot(name);
5691 if (funcp)
5692 debug_printf_exec("found function '%s'\n", name);
5693 return funcp;
5694}
5695
5696/* Note: takes ownership on name ptr */
5697static struct function *new_function(char *name)
5698{
5699 struct function **funcpp = find_function_slot(name);
5700 struct function *funcp = *funcpp;
5701
5702 if (funcp != NULL) {
5703 struct command *cmd = funcp->parent_cmd;
5704 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5705 if (!cmd) {
5706 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5707 free(funcp->name);
5708 /* Note: if !funcp->body, do not free body_as_string!
5709 * This is a special case of "-F name body" function:
5710 * body_as_string was not malloced! */
5711 if (funcp->body) {
5712 free_pipe_list(funcp->body);
5713# if !BB_MMU
5714 free(funcp->body_as_string);
5715# endif
5716 }
5717 } else {
5718 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5719 cmd->argv[0] = funcp->name;
5720 cmd->group = funcp->body;
5721# if !BB_MMU
5722 cmd->group_as_string = funcp->body_as_string;
5723# endif
5724 }
5725 } else {
5726 debug_printf_exec("remembering new function '%s'\n", name);
5727 funcp = *funcpp = xzalloc(sizeof(*funcp));
5728 /*funcp->next = NULL;*/
5729 }
5730
5731 funcp->name = name;
5732 return funcp;
5733}
5734
5735static void unset_func(const char *name)
5736{
5737 struct function **funcpp = find_function_slot(name);
5738 struct function *funcp = *funcpp;
5739
5740 if (funcp != NULL) {
5741 debug_printf_exec("freeing function '%s'\n", funcp->name);
5742 *funcpp = funcp->next;
5743 /* funcp is unlinked now, deleting it.
5744 * Note: if !funcp->body, the function was created by
5745 * "-F name body", do not free ->body_as_string
5746 * and ->name as they were not malloced. */
5747 if (funcp->body) {
5748 free_pipe_list(funcp->body);
5749 free(funcp->name);
5750# if !BB_MMU
5751 free(funcp->body_as_string);
5752# endif
5753 }
5754 free(funcp);
5755 }
5756}
5757
5758# if BB_MMU
5759#define exec_function(to_free, funcp, argv) \
5760 exec_function(funcp, argv)
5761# endif
5762static void exec_function(char ***to_free,
5763 const struct function *funcp,
5764 char **argv) NORETURN;
5765static void exec_function(char ***to_free,
5766 const struct function *funcp,
5767 char **argv)
5768{
5769# if BB_MMU
5770 int n = 1;
5771
5772 argv[0] = G.global_argv[0];
5773 G.global_argv = argv;
5774 while (*++argv)
5775 n++;
5776 G.global_argc = n;
5777 /* On MMU, funcp->body is always non-NULL */
5778 n = run_list(funcp->body);
5779 fflush_all();
5780 _exit(n);
5781# else
5782 re_execute_shell(to_free,
5783 funcp->body_as_string,
5784 G.global_argv[0],
5785 argv + 1,
5786 NULL);
5787# endif
5788}
5789
5790static int run_function(const struct function *funcp, char **argv)
5791{
5792 int rc;
5793 save_arg_t sv;
5794 smallint sv_flg;
5795
5796 save_and_replace_G_args(&sv, argv);
5797
5798 /* "we are in function, ok to use return" */
5799 sv_flg = G.flag_return_in_progress;
5800 G.flag_return_in_progress = -1;
5801# if ENABLE_HUSH_LOCAL
5802 G.func_nest_level++;
5803# endif
5804
5805 /* On MMU, funcp->body is always non-NULL */
5806# if !BB_MMU
5807 if (!funcp->body) {
5808 /* Function defined by -F */
5809 parse_and_run_string(funcp->body_as_string);
5810 rc = G.last_exitcode;
5811 } else
5812# endif
5813 {
5814 rc = run_list(funcp->body);
5815 }
5816
5817# if ENABLE_HUSH_LOCAL
5818 {
5819 struct variable *var;
5820 struct variable **var_pp;
5821
5822 var_pp = &G.top_var;
5823 while ((var = *var_pp) != NULL) {
5824 if (var->func_nest_level < G.func_nest_level) {
5825 var_pp = &var->next;
5826 continue;
5827 }
5828 /* Unexport */
5829 if (var->flg_export)
5830 bb_unsetenv(var->varstr);
5831 /* Remove from global list */
5832 *var_pp = var->next;
5833 /* Free */
5834 if (!var->max_len)
5835 free(var->varstr);
5836 free(var);
5837 }
5838 G.func_nest_level--;
5839 }
5840# endif
5841 G.flag_return_in_progress = sv_flg;
5842
5843 restore_G_args(&sv, argv);
5844
5845 return rc;
5846}
5847#endif /* ENABLE_HUSH_FUNCTIONS */
5848
5849
5850#if BB_MMU
5851#define exec_builtin(to_free, x, argv) \
5852 exec_builtin(x, argv)
5853#else
5854#define exec_builtin(to_free, x, argv) \
5855 exec_builtin(to_free, argv)
5856#endif
5857static void exec_builtin(char ***to_free,
5858 const struct built_in_command *x,
5859 char **argv) NORETURN;
5860static void exec_builtin(char ***to_free,
5861 const struct built_in_command *x,
5862 char **argv)
5863{
5864#if BB_MMU
5865 int rcode = x->b_function(argv);
5866 fflush_all();
5867 _exit(rcode);
5868#else
5869 /* On NOMMU, we must never block!
5870 * Example: { sleep 99 | read line; } & echo Ok
5871 */
5872 re_execute_shell(to_free,
5873 argv[0],
5874 G.global_argv[0],
5875 G.global_argv + 1,
5876 argv);
5877#endif
5878}
5879
5880
5881static void execvp_or_die(char **argv) NORETURN;
5882static void execvp_or_die(char **argv)
5883{
5884 debug_printf_exec("execing '%s'\n", argv[0]);
5885 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5886 execvp(argv[0], argv);
5887 bb_perror_msg("can't execute '%s'", argv[0]);
5888 _exit(127); /* bash compat */
5889}
5890
5891#if ENABLE_HUSH_MODE_X
5892static void dump_cmd_in_x_mode(char **argv)
5893{
5894 if (G_x_mode && argv) {
5895 /* We want to output the line in one write op */
5896 char *buf, *p;
5897 int len;
5898 int n;
5899
5900 len = 3;
5901 n = 0;
5902 while (argv[n])
5903 len += strlen(argv[n++]) + 1;
5904 buf = xmalloc(len);
5905 buf[0] = '+';
5906 p = buf + 1;
5907 n = 0;
5908 while (argv[n])
5909 p += sprintf(p, " %s", argv[n++]);
5910 *p++ = '\n';
5911 *p = '\0';
5912 fputs(buf, stderr);
5913 free(buf);
5914 }
5915}
5916#else
5917# define dump_cmd_in_x_mode(argv) ((void)0)
5918#endif
5919
5920#if BB_MMU
5921#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5922 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5923#define pseudo_exec(nommu_save, command, argv_expanded) \
5924 pseudo_exec(command, argv_expanded)
5925#endif
5926
5927/* Called after [v]fork() in run_pipe, or from builtin_exec.
5928 * Never returns.
5929 * Don't exit() here. If you don't exec, use _exit instead.
5930 * The at_exit handlers apparently confuse the calling process,
5931 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5932static void pseudo_exec_argv(nommu_save_t *nommu_save,
5933 char **argv, int assignment_cnt,
5934 char **argv_expanded) NORETURN;
5935static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5936 char **argv, int assignment_cnt,
5937 char **argv_expanded)
5938{
5939 char **new_env;
5940
5941 new_env = expand_assignments(argv, assignment_cnt);
5942 dump_cmd_in_x_mode(new_env);
5943
5944 if (!argv[assignment_cnt]) {
5945 /* Case when we are here: ... | var=val | ...
5946 * (note that we do not exit early, i.e., do not optimize out
5947 * expand_assignments(): think about ... | var=`sleep 1` | ...
5948 */
5949 free_strings(new_env);
5950 _exit(EXIT_SUCCESS);
5951 }
5952
5953#if BB_MMU
5954 set_vars_and_save_old(new_env);
5955 free(new_env); /* optional */
5956 /* we can also destroy set_vars_and_save_old's return value,
5957 * to save memory */
5958#else
5959 nommu_save->new_env = new_env;
5960 nommu_save->old_vars = set_vars_and_save_old(new_env);
5961#endif
5962
5963 if (argv_expanded) {
5964 argv = argv_expanded;
5965 } else {
5966 argv = expand_strvec_to_strvec(argv + assignment_cnt);
5967#if !BB_MMU
5968 nommu_save->argv = argv;
5969#endif
5970 }
5971 dump_cmd_in_x_mode(argv);
5972
5973#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
5974 if (strchr(argv[0], '/') != NULL)
5975 goto skip;
5976#endif
5977
5978 /* Check if the command matches any of the builtins.
5979 * Depending on context, this might be redundant. But it's
5980 * easier to waste a few CPU cycles than it is to figure out
5981 * if this is one of those cases.
5982 */
5983 {
5984 /* On NOMMU, it is more expensive to re-execute shell
5985 * just in order to run echo or test builtin.
5986 * It's better to skip it here and run corresponding
5987 * non-builtin later. */
5988 const struct built_in_command *x;
5989 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
5990 if (x) {
5991 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
5992 }
5993 }
5994#if ENABLE_HUSH_FUNCTIONS
5995 /* Check if the command matches any functions */
5996 {
5997 const struct function *funcp = find_function(argv[0]);
5998 if (funcp) {
5999 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6000 }
6001 }
6002#endif
6003
6004#if ENABLE_FEATURE_SH_STANDALONE
6005 /* Check if the command matches any busybox applets */
6006 {
6007 int a = find_applet_by_name(argv[0]);
6008 if (a >= 0) {
6009# if BB_MMU /* see above why on NOMMU it is not allowed */
6010 if (APPLET_IS_NOEXEC(a)) {
6011 debug_printf_exec("running applet '%s'\n", argv[0]);
6012 run_applet_no_and_exit(a, argv);
6013 }
6014# endif
6015 /* Re-exec ourselves */
6016 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6017 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6018 execv(bb_busybox_exec_path, argv);
6019 /* If they called chroot or otherwise made the binary no longer
6020 * executable, fall through */
6021 }
6022 }
6023#endif
6024
6025#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6026 skip:
6027#endif
6028 execvp_or_die(argv);
6029}
6030
6031/* Called after [v]fork() in run_pipe
6032 */
6033static void pseudo_exec(nommu_save_t *nommu_save,
6034 struct command *command,
6035 char **argv_expanded) NORETURN;
6036static void pseudo_exec(nommu_save_t *nommu_save,
6037 struct command *command,
6038 char **argv_expanded)
6039{
6040 if (command->argv) {
6041 pseudo_exec_argv(nommu_save, command->argv,
6042 command->assignment_cnt, argv_expanded);
6043 }
6044
6045 if (command->group) {
6046 /* Cases when we are here:
6047 * ( list )
6048 * { list } &
6049 * ... | ( list ) | ...
6050 * ... | { list } | ...
6051 */
6052#if BB_MMU
6053 int rcode;
6054 debug_printf_exec("pseudo_exec: run_list\n");
6055 reset_traps_to_defaults();
6056 rcode = run_list(command->group);
6057 /* OK to leak memory by not calling free_pipe_list,
6058 * since this process is about to exit */
6059 _exit(rcode);
6060#else
6061 re_execute_shell(&nommu_save->argv_from_re_execing,
6062 command->group_as_string,
6063 G.global_argv[0],
6064 G.global_argv + 1,
6065 NULL);
6066#endif
6067 }
6068
6069 /* Case when we are here: ... | >file */
6070 debug_printf_exec("pseudo_exec'ed null command\n");
6071 _exit(EXIT_SUCCESS);
6072}
6073
6074#if ENABLE_HUSH_JOB
6075static const char *get_cmdtext(struct pipe *pi)
6076{
6077 char **argv;
6078 char *p;
6079 int len;
6080
6081 /* This is subtle. ->cmdtext is created only on first backgrounding.
6082 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6083 * On subsequent bg argv is trashed, but we won't use it */
6084 if (pi->cmdtext)
6085 return pi->cmdtext;
6086 argv = pi->cmds[0].argv;
6087 if (!argv || !argv[0]) {
6088 pi->cmdtext = xzalloc(1);
6089 return pi->cmdtext;
6090 }
6091
6092 len = 0;
6093 do {
6094 len += strlen(*argv) + 1;
6095 } while (*++argv);
6096 p = xmalloc(len);
6097 pi->cmdtext = p;
6098 argv = pi->cmds[0].argv;
6099 do {
6100 len = strlen(*argv);
6101 memcpy(p, *argv, len);
6102 p += len;
6103 *p++ = ' ';
6104 } while (*++argv);
6105 p[-1] = '\0';
6106 return pi->cmdtext;
6107}
6108
6109static void insert_bg_job(struct pipe *pi)
6110{
6111 struct pipe *job, **jobp;
6112 int i;
6113
6114 /* Linear search for the ID of the job to use */
6115 pi->jobid = 1;
6116 for (job = G.job_list; job; job = job->next)
6117 if (job->jobid >= pi->jobid)
6118 pi->jobid = job->jobid + 1;
6119
6120 /* Add job to the list of running jobs */
6121 jobp = &G.job_list;
6122 while ((job = *jobp) != NULL)
6123 jobp = &job->next;
6124 job = *jobp = xmalloc(sizeof(*job));
6125
6126 *job = *pi; /* physical copy */
6127 job->next = NULL;
6128 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6129 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6130 for (i = 0; i < pi->num_cmds; i++) {
6131 job->cmds[i].pid = pi->cmds[i].pid;
6132 /* all other fields are not used and stay zero */
6133 }
6134 job->cmdtext = xstrdup(get_cmdtext(pi));
6135
6136 if (G_interactive_fd)
6137 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6138 G.last_jobid = job->jobid;
6139}
6140
6141static void remove_bg_job(struct pipe *pi)
6142{
6143 struct pipe *prev_pipe;
6144
6145 if (pi == G.job_list) {
6146 G.job_list = pi->next;
6147 } else {
6148 prev_pipe = G.job_list;
6149 while (prev_pipe->next != pi)
6150 prev_pipe = prev_pipe->next;
6151 prev_pipe->next = pi->next;
6152 }
6153 if (G.job_list)
6154 G.last_jobid = G.job_list->jobid;
6155 else
6156 G.last_jobid = 0;
6157}
6158
6159/* Remove a backgrounded job */
6160static void delete_finished_bg_job(struct pipe *pi)
6161{
6162 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006163 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006164}
6165#endif /* JOB */
6166
6167/* Check to see if any processes have exited -- if they
6168 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006169static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006170{
6171 int attributes;
6172 int status;
6173#if ENABLE_HUSH_JOB
6174 struct pipe *pi;
6175#endif
6176 pid_t childpid;
6177 int rcode = 0;
6178
6179 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6180
6181 attributes = WUNTRACED;
6182 if (fg_pipe == NULL)
6183 attributes |= WNOHANG;
6184
6185 errno = 0;
6186#if ENABLE_HUSH_FAST
6187 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6188//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6189//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6190 /* There was neither fork nor SIGCHLD since last waitpid */
6191 /* Avoid doing waitpid syscall if possible */
6192 if (!G.we_have_children) {
6193 errno = ECHILD;
6194 return -1;
6195 }
6196 if (fg_pipe == NULL) { /* is WNOHANG set? */
6197 /* We have children, but they did not exit
6198 * or stop yet (we saw no SIGCHLD) */
6199 return 0;
6200 }
6201 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6202 }
6203#endif
6204
6205/* Do we do this right?
6206 * bash-3.00# sleep 20 | false
6207 * <ctrl-Z pressed>
6208 * [3]+ Stopped sleep 20 | false
6209 * bash-3.00# echo $?
6210 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6211 * [hush 1.14.0: yes we do it right]
6212 */
6213 wait_more:
6214 while (1) {
6215 int i;
6216 int dead;
6217
6218#if ENABLE_HUSH_FAST
6219 i = G.count_SIGCHLD;
6220#endif
6221 childpid = waitpid(-1, &status, attributes);
6222 if (childpid <= 0) {
6223 if (childpid && errno != ECHILD)
6224 bb_perror_msg("waitpid");
6225#if ENABLE_HUSH_FAST
6226 else { /* Until next SIGCHLD, waitpid's are useless */
6227 G.we_have_children = (childpid == 0);
6228 G.handled_SIGCHLD = i;
6229//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6230 }
6231#endif
6232 break;
6233 }
6234 dead = WIFEXITED(status) || WIFSIGNALED(status);
6235
6236#if DEBUG_JOBS
6237 if (WIFSTOPPED(status))
6238 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6239 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6240 if (WIFSIGNALED(status))
6241 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6242 childpid, WTERMSIG(status), WEXITSTATUS(status));
6243 if (WIFEXITED(status))
6244 debug_printf_jobs("pid %d exited, exitcode %d\n",
6245 childpid, WEXITSTATUS(status));
6246#endif
6247 /* Were we asked to wait for fg pipe? */
6248 if (fg_pipe) {
6249 for (i = 0; i < fg_pipe->num_cmds; i++) {
6250 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6251 if (fg_pipe->cmds[i].pid != childpid)
6252 continue;
6253 if (dead) {
6254 fg_pipe->cmds[i].pid = 0;
6255 fg_pipe->alive_cmds--;
6256 if (i == fg_pipe->num_cmds - 1) {
6257 /* last process gives overall exitstatus */
6258 rcode = WEXITSTATUS(status);
6259 /* bash prints killer signal's name for *last*
6260 * process in pipe (prints just newline for SIGINT).
6261 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6262 */
6263 if (WIFSIGNALED(status)) {
6264 int sig = WTERMSIG(status);
6265 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6266 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6267 * Maybe we need to use sig | 128? */
6268 rcode = sig + 128;
6269 }
6270 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6271 }
6272 } else {
6273 fg_pipe->cmds[i].is_stopped = 1;
6274 fg_pipe->stopped_cmds++;
6275 }
6276 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6277 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6278 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6279 /* All processes in fg pipe have exited or stopped */
6280/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6281 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6282 * and "killall -STOP cat" */
6283 if (G_interactive_fd) {
6284#if ENABLE_HUSH_JOB
6285 if (fg_pipe->alive_cmds)
6286 insert_bg_job(fg_pipe);
6287#endif
6288 return rcode;
6289 }
6290 if (!fg_pipe->alive_cmds)
6291 return rcode;
6292 }
6293 /* There are still running processes in the fg pipe */
6294 goto wait_more; /* do waitpid again */
6295 }
6296 /* it wasnt fg_pipe, look for process in bg pipes */
6297 }
6298
6299#if ENABLE_HUSH_JOB
6300 /* We asked to wait for bg or orphaned children */
6301 /* No need to remember exitcode in this case */
6302 for (pi = G.job_list; pi; pi = pi->next) {
6303 for (i = 0; i < pi->num_cmds; i++) {
6304 if (pi->cmds[i].pid == childpid)
6305 goto found_pi_and_prognum;
6306 }
6307 }
6308 /* Happens when shell is used as init process (init=/bin/sh) */
6309 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6310 continue; /* do waitpid again */
6311
6312 found_pi_and_prognum:
6313 if (dead) {
6314 /* child exited */
6315 pi->cmds[i].pid = 0;
6316 pi->alive_cmds--;
6317 if (!pi->alive_cmds) {
6318 if (G_interactive_fd)
6319 printf(JOB_STATUS_FORMAT, pi->jobid,
6320 "Done", pi->cmdtext);
6321 delete_finished_bg_job(pi);
6322 }
6323 } else {
6324 /* child stopped */
6325 pi->cmds[i].is_stopped = 1;
6326 pi->stopped_cmds++;
6327 }
6328#endif
6329 } /* while (waitpid succeeds)... */
6330
6331 return rcode;
6332}
6333
6334#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006335static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006336{
6337 pid_t p;
6338 int rcode = checkjobs(fg_pipe);
6339 if (G_saved_tty_pgrp) {
6340 /* Job finished, move the shell to the foreground */
6341 p = getpgrp(); /* our process group id */
6342 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6343 tcsetpgrp(G_interactive_fd, p);
6344 }
6345 return rcode;
6346}
6347#endif
6348
6349/* Start all the jobs, but don't wait for anything to finish.
6350 * See checkjobs().
6351 *
6352 * Return code is normally -1, when the caller has to wait for children
6353 * to finish to determine the exit status of the pipe. If the pipe
6354 * is a simple builtin command, however, the action is done by the
6355 * time run_pipe returns, and the exit code is provided as the
6356 * return value.
6357 *
6358 * Returns -1 only if started some children. IOW: we have to
6359 * mask out retvals of builtins etc with 0xff!
6360 *
6361 * The only case when we do not need to [v]fork is when the pipe
6362 * is single, non-backgrounded, non-subshell command. Examples:
6363 * cmd ; ... { list } ; ...
6364 * cmd && ... { list } && ...
6365 * cmd || ... { list } || ...
6366 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6367 * or (if SH_STANDALONE) an applet, and we can run the { list }
6368 * with run_list. If it isn't one of these, we fork and exec cmd.
6369 *
6370 * Cases when we must fork:
6371 * non-single: cmd | cmd
6372 * backgrounded: cmd & { list } &
6373 * subshell: ( list ) [&]
6374 */
6375#if !ENABLE_HUSH_MODE_X
6376#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6377 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6378#endif
6379static int redirect_and_varexp_helper(char ***new_env_p,
6380 struct variable **old_vars_p,
6381 struct command *command,
6382 int squirrel[3],
6383 char **argv_expanded)
6384{
6385 /* setup_redirects acts on file descriptors, not FILEs.
6386 * This is perfect for work that comes after exec().
6387 * Is it really safe for inline use? Experimentally,
6388 * things seem to work. */
6389 int rcode = setup_redirects(command, squirrel);
6390 if (rcode == 0) {
6391 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6392 *new_env_p = new_env;
6393 dump_cmd_in_x_mode(new_env);
6394 dump_cmd_in_x_mode(argv_expanded);
6395 if (old_vars_p)
6396 *old_vars_p = set_vars_and_save_old(new_env);
6397 }
6398 return rcode;
6399}
6400static NOINLINE int run_pipe(struct pipe *pi)
6401{
6402 static const char *const null_ptr = NULL;
6403
6404 int cmd_no;
6405 int next_infd;
6406 struct command *command;
6407 char **argv_expanded;
6408 char **argv;
6409 /* it is not always needed, but we aim to smaller code */
6410 int squirrel[] = { -1, -1, -1 };
6411 int rcode;
6412
6413 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6414 debug_enter();
6415
6416 IF_HUSH_JOB(pi->pgrp = -1;)
6417 pi->stopped_cmds = 0;
6418 command = &pi->cmds[0];
6419 argv_expanded = NULL;
6420
6421 if (pi->num_cmds != 1
6422 || pi->followup == PIPE_BG
6423 || command->cmd_type == CMD_SUBSHELL
6424 ) {
6425 goto must_fork;
6426 }
6427
6428 pi->alive_cmds = 1;
6429
6430 debug_printf_exec(": group:%p argv:'%s'\n",
6431 command->group, command->argv ? command->argv[0] : "NONE");
6432
6433 if (command->group) {
6434#if ENABLE_HUSH_FUNCTIONS
6435 if (command->cmd_type == CMD_FUNCDEF) {
6436 /* "executing" func () { list } */
6437 struct function *funcp;
6438
6439 funcp = new_function(command->argv[0]);
6440 /* funcp->name is already set to argv[0] */
6441 funcp->body = command->group;
6442# if !BB_MMU
6443 funcp->body_as_string = command->group_as_string;
6444 command->group_as_string = NULL;
6445# endif
6446 command->group = NULL;
6447 command->argv[0] = NULL;
6448 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6449 funcp->parent_cmd = command;
6450 command->child_func = funcp;
6451
6452 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6453 debug_leave();
6454 return EXIT_SUCCESS;
6455 }
6456#endif
6457 /* { list } */
6458 debug_printf("non-subshell group\n");
6459 rcode = 1; /* exitcode if redir failed */
6460 if (setup_redirects(command, squirrel) == 0) {
6461 debug_printf_exec(": run_list\n");
6462 rcode = run_list(command->group) & 0xff;
6463 }
6464 restore_redirects(squirrel);
6465 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6466 debug_leave();
6467 debug_printf_exec("run_pipe: return %d\n", rcode);
6468 return rcode;
6469 }
6470
6471 argv = command->argv ? command->argv : (char **) &null_ptr;
6472 {
6473 const struct built_in_command *x;
6474#if ENABLE_HUSH_FUNCTIONS
6475 const struct function *funcp;
6476#else
6477 enum { funcp = 0 };
6478#endif
6479 char **new_env = NULL;
6480 struct variable *old_vars = NULL;
6481
6482 if (argv[command->assignment_cnt] == NULL) {
6483 /* Assignments, but no command */
6484 /* Ensure redirects take effect (that is, create files).
6485 * Try "a=t >file" */
6486#if 0 /* A few cases in testsuite fail with this code. FIXME */
6487 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6488 /* Set shell variables */
6489 if (new_env) {
6490 argv = new_env;
6491 while (*argv) {
6492 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6493 /* Do we need to flag set_local_var() errors?
6494 * "assignment to readonly var" and "putenv error"
6495 */
6496 argv++;
6497 }
6498 }
6499 /* Redirect error sets $? to 1. Otherwise,
6500 * if evaluating assignment value set $?, retain it.
6501 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6502 if (rcode == 0)
6503 rcode = G.last_exitcode;
6504 /* Exit, _skipping_ variable restoring code: */
6505 goto clean_up_and_ret0;
6506
6507#else /* Older, bigger, but more correct code */
6508
6509 rcode = setup_redirects(command, squirrel);
6510 restore_redirects(squirrel);
6511 /* Set shell variables */
6512 if (G_x_mode)
6513 bb_putchar_stderr('+');
6514 while (*argv) {
6515 char *p = expand_string_to_string(*argv);
6516 if (G_x_mode)
6517 fprintf(stderr, " %s", p);
6518 debug_printf_exec("set shell var:'%s'->'%s'\n",
6519 *argv, p);
6520 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6521 /* Do we need to flag set_local_var() errors?
6522 * "assignment to readonly var" and "putenv error"
6523 */
6524 argv++;
6525 }
6526 if (G_x_mode)
6527 bb_putchar_stderr('\n');
6528 /* Redirect error sets $? to 1. Otherwise,
6529 * if evaluating assignment value set $?, retain it.
6530 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6531 if (rcode == 0)
6532 rcode = G.last_exitcode;
6533 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6534 debug_leave();
6535 debug_printf_exec("run_pipe: return %d\n", rcode);
6536 return rcode;
6537#endif
6538 }
6539
6540 /* Expand the rest into (possibly) many strings each */
6541 if (0) {}
6542#if ENABLE_HUSH_BASH_COMPAT
6543 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6544 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6545 }
6546#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006547 else {
6548 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6549 }
6550
6551 /* if someone gives us an empty string: `cmd with empty output` */
6552 if (!argv_expanded[0]) {
6553 free(argv_expanded);
6554 debug_leave();
6555 return G.last_exitcode;
6556 }
6557
6558 x = find_builtin(argv_expanded[0]);
6559#if ENABLE_HUSH_FUNCTIONS
6560 funcp = NULL;
6561 if (!x)
6562 funcp = find_function(argv_expanded[0]);
6563#endif
6564 if (x || funcp) {
6565 if (!funcp) {
6566 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6567 debug_printf("exec with redirects only\n");
6568 rcode = setup_redirects(command, NULL);
6569 goto clean_up_and_ret1;
6570 }
6571 }
6572 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6573 if (rcode == 0) {
6574 if (!funcp) {
6575 debug_printf_exec(": builtin '%s' '%s'...\n",
6576 x->b_cmd, argv_expanded[1]);
6577 rcode = x->b_function(argv_expanded) & 0xff;
6578 fflush_all();
6579 }
6580#if ENABLE_HUSH_FUNCTIONS
6581 else {
6582# if ENABLE_HUSH_LOCAL
6583 struct variable **sv;
6584 sv = G.shadowed_vars_pp;
6585 G.shadowed_vars_pp = &old_vars;
6586# endif
6587 debug_printf_exec(": function '%s' '%s'...\n",
6588 funcp->name, argv_expanded[1]);
6589 rcode = run_function(funcp, argv_expanded) & 0xff;
6590# if ENABLE_HUSH_LOCAL
6591 G.shadowed_vars_pp = sv;
6592# endif
6593 }
6594#endif
6595 }
6596 clean_up_and_ret:
6597 unset_vars(new_env);
6598 add_vars(old_vars);
6599/* clean_up_and_ret0: */
6600 restore_redirects(squirrel);
6601 clean_up_and_ret1:
6602 free(argv_expanded);
6603 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6604 debug_leave();
6605 debug_printf_exec("run_pipe return %d\n", rcode);
6606 return rcode;
6607 }
6608
6609 if (ENABLE_FEATURE_SH_STANDALONE) {
6610 int n = find_applet_by_name(argv_expanded[0]);
6611 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6612 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6613 if (rcode == 0) {
6614 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6615 argv_expanded[0], argv_expanded[1]);
6616 rcode = run_nofork_applet(n, argv_expanded);
6617 }
6618 goto clean_up_and_ret;
6619 }
6620 }
6621 /* It is neither builtin nor applet. We must fork. */
6622 }
6623
6624 must_fork:
6625 /* NB: argv_expanded may already be created, and that
6626 * might include `cmd` runs! Do not rerun it! We *must*
6627 * use argv_expanded if it's non-NULL */
6628
6629 /* Going to fork a child per each pipe member */
6630 pi->alive_cmds = 0;
6631 next_infd = 0;
6632
6633 cmd_no = 0;
6634 while (cmd_no < pi->num_cmds) {
6635 struct fd_pair pipefds;
6636#if !BB_MMU
6637 volatile nommu_save_t nommu_save;
6638 nommu_save.new_env = NULL;
6639 nommu_save.old_vars = NULL;
6640 nommu_save.argv = NULL;
6641 nommu_save.argv_from_re_execing = NULL;
6642#endif
6643 command = &pi->cmds[cmd_no];
6644 cmd_no++;
6645 if (command->argv) {
6646 debug_printf_exec(": pipe member '%s' '%s'...\n",
6647 command->argv[0], command->argv[1]);
6648 } else {
6649 debug_printf_exec(": pipe member with no argv\n");
6650 }
6651
6652 /* pipes are inserted between pairs of commands */
6653 pipefds.rd = 0;
6654 pipefds.wr = 1;
6655 if (cmd_no < pi->num_cmds)
6656 xpiped_pair(pipefds);
6657
6658 command->pid = BB_MMU ? fork() : vfork();
6659 if (!command->pid) { /* child */
6660#if ENABLE_HUSH_JOB
6661 disable_restore_tty_pgrp_on_exit();
6662 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6663
6664 /* Every child adds itself to new process group
6665 * with pgid == pid_of_first_child_in_pipe */
6666 if (G.run_list_level == 1 && G_interactive_fd) {
6667 pid_t pgrp;
6668 pgrp = pi->pgrp;
6669 if (pgrp < 0) /* true for 1st process only */
6670 pgrp = getpid();
6671 if (setpgid(0, pgrp) == 0
6672 && pi->followup != PIPE_BG
6673 && G_saved_tty_pgrp /* we have ctty */
6674 ) {
6675 /* We do it in *every* child, not just first,
6676 * to avoid races */
6677 tcsetpgrp(G_interactive_fd, pgrp);
6678 }
6679 }
6680#endif
6681 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6682 /* 1st cmd in backgrounded pipe
6683 * should have its stdin /dev/null'ed */
6684 close(0);
6685 if (open(bb_dev_null, O_RDONLY))
6686 xopen("/", O_RDONLY);
6687 } else {
6688 xmove_fd(next_infd, 0);
6689 }
6690 xmove_fd(pipefds.wr, 1);
6691 if (pipefds.rd > 1)
6692 close(pipefds.rd);
6693 /* Like bash, explicit redirects override pipes,
6694 * and the pipe fd is available for dup'ing. */
6695 if (setup_redirects(command, NULL))
6696 _exit(1);
6697
6698 /* Restore default handlers just prior to exec */
6699 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6700
6701 /* Stores to nommu_save list of env vars putenv'ed
6702 * (NOMMU, on MMU we don't need that) */
6703 /* cast away volatility... */
6704 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6705 /* pseudo_exec() does not return */
6706 }
6707
6708 /* parent or error */
6709#if ENABLE_HUSH_FAST
6710 G.count_SIGCHLD++;
6711//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6712#endif
6713 enable_restore_tty_pgrp_on_exit();
6714#if !BB_MMU
6715 /* Clean up after vforked child */
6716 free(nommu_save.argv);
6717 free(nommu_save.argv_from_re_execing);
6718 unset_vars(nommu_save.new_env);
6719 add_vars(nommu_save.old_vars);
6720#endif
6721 free(argv_expanded);
6722 argv_expanded = NULL;
6723 if (command->pid < 0) { /* [v]fork failed */
6724 /* Clearly indicate, was it fork or vfork */
6725 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6726 } else {
6727 pi->alive_cmds++;
6728#if ENABLE_HUSH_JOB
6729 /* Second and next children need to know pid of first one */
6730 if (pi->pgrp < 0)
6731 pi->pgrp = command->pid;
6732#endif
6733 }
6734
6735 if (cmd_no > 1)
6736 close(next_infd);
6737 if (cmd_no < pi->num_cmds)
6738 close(pipefds.wr);
6739 /* Pass read (output) pipe end to next iteration */
6740 next_infd = pipefds.rd;
6741 }
6742
6743 if (!pi->alive_cmds) {
6744 debug_leave();
6745 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6746 return 1;
6747 }
6748
6749 debug_leave();
6750 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6751 return -1;
6752}
6753
6754#ifndef debug_print_tree
6755static void debug_print_tree(struct pipe *pi, int lvl)
6756{
6757 static const char *const PIPE[] = {
6758 [PIPE_SEQ] = "SEQ",
6759 [PIPE_AND] = "AND",
6760 [PIPE_OR ] = "OR" ,
6761 [PIPE_BG ] = "BG" ,
6762 };
6763 static const char *RES[] = {
6764 [RES_NONE ] = "NONE" ,
6765# if ENABLE_HUSH_IF
6766 [RES_IF ] = "IF" ,
6767 [RES_THEN ] = "THEN" ,
6768 [RES_ELIF ] = "ELIF" ,
6769 [RES_ELSE ] = "ELSE" ,
6770 [RES_FI ] = "FI" ,
6771# endif
6772# if ENABLE_HUSH_LOOPS
6773 [RES_FOR ] = "FOR" ,
6774 [RES_WHILE] = "WHILE",
6775 [RES_UNTIL] = "UNTIL",
6776 [RES_DO ] = "DO" ,
6777 [RES_DONE ] = "DONE" ,
6778# endif
6779# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6780 [RES_IN ] = "IN" ,
6781# endif
6782# if ENABLE_HUSH_CASE
6783 [RES_CASE ] = "CASE" ,
6784 [RES_CASE_IN ] = "CASE_IN" ,
6785 [RES_MATCH] = "MATCH",
6786 [RES_CASE_BODY] = "CASE_BODY",
6787 [RES_ESAC ] = "ESAC" ,
6788# endif
6789 [RES_XXXX ] = "XXXX" ,
6790 [RES_SNTX ] = "SNTX" ,
6791 };
6792 static const char *const CMDTYPE[] = {
6793 "{}",
6794 "()",
6795 "[noglob]",
6796# if ENABLE_HUSH_FUNCTIONS
6797 "func()",
6798# endif
6799 };
6800
6801 int pin, prn;
6802
6803 pin = 0;
6804 while (pi) {
6805 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6806 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6807 prn = 0;
6808 while (prn < pi->num_cmds) {
6809 struct command *command = &pi->cmds[prn];
6810 char **argv = command->argv;
6811
6812 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6813 lvl*2, "", prn,
6814 command->assignment_cnt);
6815 if (command->group) {
6816 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6817 CMDTYPE[command->cmd_type],
6818 argv
6819# if !BB_MMU
6820 , " group_as_string:", command->group_as_string
6821# else
6822 , "", ""
6823# endif
6824 );
6825 debug_print_tree(command->group, lvl+1);
6826 prn++;
6827 continue;
6828 }
6829 if (argv) while (*argv) {
6830 fprintf(stderr, " '%s'", *argv);
6831 argv++;
6832 }
6833 fprintf(stderr, "\n");
6834 prn++;
6835 }
6836 pi = pi->next;
6837 pin++;
6838 }
6839}
6840#endif /* debug_print_tree */
6841
6842/* NB: called by pseudo_exec, and therefore must not modify any
6843 * global data until exec/_exit (we can be a child after vfork!) */
6844static int run_list(struct pipe *pi)
6845{
6846#if ENABLE_HUSH_CASE
6847 char *case_word = NULL;
6848#endif
6849#if ENABLE_HUSH_LOOPS
6850 struct pipe *loop_top = NULL;
6851 char **for_lcur = NULL;
6852 char **for_list = NULL;
6853#endif
6854 smallint last_followup;
6855 smalluint rcode;
6856#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6857 smalluint cond_code = 0;
6858#else
6859 enum { cond_code = 0 };
6860#endif
6861#if HAS_KEYWORDS
6862 smallint rword; /* enum reserved_style */
6863 smallint last_rword; /* ditto */
6864#endif
6865
6866 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6867 debug_enter();
6868
6869#if ENABLE_HUSH_LOOPS
6870 /* Check syntax for "for" */
6871 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6872 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6873 continue;
6874 /* current word is FOR or IN (BOLD in comments below) */
6875 if (cpipe->next == NULL) {
6876 syntax_error("malformed for");
6877 debug_leave();
6878 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6879 return 1;
6880 }
6881 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6882 if (cpipe->next->res_word == RES_DO)
6883 continue;
6884 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6885 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6886 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6887 ) {
6888 syntax_error("malformed for");
6889 debug_leave();
6890 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6891 return 1;
6892 }
6893 }
6894#endif
6895
6896 /* Past this point, all code paths should jump to ret: label
6897 * in order to return, no direct "return" statements please.
6898 * This helps to ensure that no memory is leaked. */
6899
6900#if ENABLE_HUSH_JOB
6901 G.run_list_level++;
6902#endif
6903
6904#if HAS_KEYWORDS
6905 rword = RES_NONE;
6906 last_rword = RES_XXXX;
6907#endif
6908 last_followup = PIPE_SEQ;
6909 rcode = G.last_exitcode;
6910
6911 /* Go through list of pipes, (maybe) executing them. */
6912 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6913 if (G.flag_SIGINT)
6914 break;
6915
6916 IF_HAS_KEYWORDS(rword = pi->res_word;)
6917 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6918 rword, cond_code, last_rword);
6919#if ENABLE_HUSH_LOOPS
6920 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6921 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6922 ) {
6923 /* start of a loop: remember where loop starts */
6924 loop_top = pi;
6925 G.depth_of_loop++;
6926 }
6927#endif
6928 /* Still in the same "if...", "then..." or "do..." branch? */
6929 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6930 if ((rcode == 0 && last_followup == PIPE_OR)
6931 || (rcode != 0 && last_followup == PIPE_AND)
6932 ) {
6933 /* It is "<true> || CMD" or "<false> && CMD"
6934 * and we should not execute CMD */
6935 debug_printf_exec("skipped cmd because of || or &&\n");
6936 last_followup = pi->followup;
6937 continue;
6938 }
6939 }
6940 last_followup = pi->followup;
6941 IF_HAS_KEYWORDS(last_rword = rword;)
6942#if ENABLE_HUSH_IF
6943 if (cond_code) {
6944 if (rword == RES_THEN) {
6945 /* if false; then ... fi has exitcode 0! */
6946 G.last_exitcode = rcode = EXIT_SUCCESS;
6947 /* "if <false> THEN cmd": skip cmd */
6948 continue;
6949 }
6950 } else {
6951 if (rword == RES_ELSE || rword == RES_ELIF) {
6952 /* "if <true> then ... ELSE/ELIF cmd":
6953 * skip cmd and all following ones */
6954 break;
6955 }
6956 }
6957#endif
6958#if ENABLE_HUSH_LOOPS
6959 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
6960 if (!for_lcur) {
6961 /* first loop through for */
6962
6963 static const char encoded_dollar_at[] ALIGN1 = {
6964 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
6965 }; /* encoded representation of "$@" */
6966 static const char *const encoded_dollar_at_argv[] = {
6967 encoded_dollar_at, NULL
6968 }; /* argv list with one element: "$@" */
6969 char **vals;
6970
6971 vals = (char**)encoded_dollar_at_argv;
6972 if (pi->next->res_word == RES_IN) {
6973 /* if no variable values after "in" we skip "for" */
6974 if (!pi->next->cmds[0].argv) {
6975 G.last_exitcode = rcode = EXIT_SUCCESS;
6976 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
6977 break;
6978 }
6979 vals = pi->next->cmds[0].argv;
6980 } /* else: "for var; do..." -> assume "$@" list */
6981 /* create list of variable values */
6982 debug_print_strings("for_list made from", vals);
6983 for_list = expand_strvec_to_strvec(vals);
6984 for_lcur = for_list;
6985 debug_print_strings("for_list", for_list);
6986 }
6987 if (!*for_lcur) {
6988 /* "for" loop is over, clean up */
6989 free(for_list);
6990 for_list = NULL;
6991 for_lcur = NULL;
6992 break;
6993 }
6994 /* Insert next value from for_lcur */
6995 /* note: *for_lcur already has quotes removed, $var expanded, etc */
6996 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6997 continue;
6998 }
6999 if (rword == RES_IN) {
7000 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7001 }
7002 if (rword == RES_DONE) {
7003 continue; /* "done" has no cmds too */
7004 }
7005#endif
7006#if ENABLE_HUSH_CASE
7007 if (rword == RES_CASE) {
7008 case_word = expand_strvec_to_string(pi->cmds->argv);
7009 continue;
7010 }
7011 if (rword == RES_MATCH) {
7012 char **argv;
7013
7014 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7015 break;
7016 /* all prev words didn't match, does this one match? */
7017 argv = pi->cmds->argv;
7018 while (*argv) {
7019 char *pattern = expand_string_to_string(*argv);
7020 /* TODO: which FNM_xxx flags to use? */
7021 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7022 free(pattern);
7023 if (cond_code == 0) { /* match! we will execute this branch */
7024 free(case_word); /* make future "word)" stop */
7025 case_word = NULL;
7026 break;
7027 }
7028 argv++;
7029 }
7030 continue;
7031 }
7032 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7033 if (cond_code != 0)
7034 continue; /* not matched yet, skip this pipe */
7035 }
7036#endif
7037 /* Just pressing <enter> in shell should check for jobs.
7038 * OTOH, in non-interactive shell this is useless
7039 * and only leads to extra job checks */
7040 if (pi->num_cmds == 0) {
7041 if (G_interactive_fd)
7042 goto check_jobs_and_continue;
7043 continue;
7044 }
7045
7046 /* After analyzing all keywords and conditions, we decided
7047 * to execute this pipe. NB: have to do checkjobs(NULL)
7048 * after run_pipe to collect any background children,
7049 * even if list execution is to be stopped. */
7050 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7051 {
7052 int r;
7053#if ENABLE_HUSH_LOOPS
7054 G.flag_break_continue = 0;
7055#endif
7056 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7057 if (r != -1) {
7058 /* We ran a builtin, function, or group.
7059 * rcode is already known
7060 * and we don't need to wait for anything. */
7061 G.last_exitcode = rcode;
7062 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7063 check_and_run_traps(0);
7064#if ENABLE_HUSH_LOOPS
7065 /* Was it "break" or "continue"? */
7066 if (G.flag_break_continue) {
7067 smallint fbc = G.flag_break_continue;
7068 /* We might fall into outer *loop*,
7069 * don't want to break it too */
7070 if (loop_top) {
7071 G.depth_break_continue--;
7072 if (G.depth_break_continue == 0)
7073 G.flag_break_continue = 0;
7074 /* else: e.g. "continue 2" should *break* once, *then* continue */
7075 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7076 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7077 goto check_jobs_and_break;
7078 /* "continue": simulate end of loop */
7079 rword = RES_DONE;
7080 continue;
7081 }
7082#endif
7083#if ENABLE_HUSH_FUNCTIONS
7084 if (G.flag_return_in_progress == 1) {
7085 /* same as "goto check_jobs_and_break" */
7086 checkjobs(NULL);
7087 break;
7088 }
7089#endif
7090 } else if (pi->followup == PIPE_BG) {
7091 /* What does bash do with attempts to background builtins? */
7092 /* even bash 3.2 doesn't do that well with nested bg:
7093 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7094 * I'm NOT treating inner &'s as jobs */
7095 check_and_run_traps(0);
7096#if ENABLE_HUSH_JOB
7097 if (G.run_list_level == 1)
7098 insert_bg_job(pi);
7099#endif
7100 /* Last command's pid goes to $! */
7101 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7102 G.last_exitcode = rcode = EXIT_SUCCESS;
7103 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7104 } else {
7105#if ENABLE_HUSH_JOB
7106 if (G.run_list_level == 1 && G_interactive_fd) {
7107 /* Waits for completion, then fg's main shell */
7108 rcode = checkjobs_and_fg_shell(pi);
7109 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7110 check_and_run_traps(0);
7111 } else
7112#endif
7113 { /* This one just waits for completion */
7114 rcode = checkjobs(pi);
7115 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7116 check_and_run_traps(0);
7117 }
7118 G.last_exitcode = rcode;
7119 }
7120 }
7121
7122 /* Analyze how result affects subsequent commands */
7123#if ENABLE_HUSH_IF
7124 if (rword == RES_IF || rword == RES_ELIF)
7125 cond_code = rcode;
7126#endif
7127#if ENABLE_HUSH_LOOPS
7128 /* Beware of "while false; true; do ..."! */
7129 if (pi->next && pi->next->res_word == RES_DO) {
7130 if (rword == RES_WHILE) {
7131 if (rcode) {
7132 /* "while false; do...done" - exitcode 0 */
7133 G.last_exitcode = rcode = EXIT_SUCCESS;
7134 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7135 goto check_jobs_and_break;
7136 }
7137 }
7138 if (rword == RES_UNTIL) {
7139 if (!rcode) {
7140 debug_printf_exec(": until expr is true: breaking\n");
7141 check_jobs_and_break:
7142 checkjobs(NULL);
7143 break;
7144 }
7145 }
7146 }
7147#endif
7148
7149 check_jobs_and_continue:
7150 checkjobs(NULL);
7151 } /* for (pi) */
7152
7153#if ENABLE_HUSH_JOB
7154 G.run_list_level--;
7155#endif
7156#if ENABLE_HUSH_LOOPS
7157 if (loop_top)
7158 G.depth_of_loop--;
7159 free(for_list);
7160#endif
7161#if ENABLE_HUSH_CASE
7162 free(case_word);
7163#endif
7164 debug_leave();
7165 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7166 return rcode;
7167}
7168
7169/* Select which version we will use */
7170static int run_and_free_list(struct pipe *pi)
7171{
7172 int rcode = 0;
7173 debug_printf_exec("run_and_free_list entered\n");
7174 if (!G.n_mode) {
7175 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7176 rcode = run_list(pi);
7177 }
7178 /* free_pipe_list has the side effect of clearing memory.
7179 * In the long run that function can be merged with run_list,
7180 * but doing that now would hobble the debugging effort. */
7181 free_pipe_list(pi);
7182 debug_printf_exec("run_and_free_list return %d\n", rcode);
7183 return rcode;
7184}
7185
7186
Denis Vlasenkof9375282009-04-05 19:13:39 +00007187/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007188static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007189{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007190 unsigned sig;
7191 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007192 sigset_t old_blocked_set;
7193
7194 if (!G.inherited_set_is_saved) {
7195 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7196 G.inherited_set = G.blocked_set;
7197 }
7198 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007199
Denis Vlasenkof9375282009-04-05 19:13:39 +00007200 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007201 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007202 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007203 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007204 mask |= SPECIAL_JOB_SIGS;
7205 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007206 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007207
Denis Vlasenkof9375282009-04-05 19:13:39 +00007208 sig = 0;
7209 while (mask) {
7210 if (mask & 1)
7211 sigaddset(&G.blocked_set, sig);
7212 mask >>= 1;
7213 sig++;
7214 }
7215 sigdelset(&G.blocked_set, SIGCHLD);
7216
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007217 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7218 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7219
Denis Vlasenkof9375282009-04-05 19:13:39 +00007220 /* POSIX allows shell to re-enable SIGCHLD
7221 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007222#if ENABLE_HUSH_FAST
7223 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007224 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007225 signal(SIGCHLD, SIGCHLD_handler);
7226#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007227 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007228 signal(SIGCHLD, SIG_DFL);
7229#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007230
7231 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007232}
7233
7234#if ENABLE_HUSH_JOB
7235/* helper */
7236static void maybe_set_to_sigexit(int sig)
7237{
7238 void (*handler)(int);
7239 /* non_DFL_mask'ed signals are, well, masked,
7240 * no need to set handler for them.
7241 */
7242 if (!((G.non_DFL_mask >> sig) & 1)) {
7243 handler = signal(sig, sigexit);
7244 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7245 signal(sig, handler);
7246 }
7247}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007248/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007249static void set_fatal_handlers(void)
7250{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007251 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007252 if (HUSH_DEBUG) {
7253 maybe_set_to_sigexit(SIGILL );
7254 maybe_set_to_sigexit(SIGFPE );
7255 maybe_set_to_sigexit(SIGBUS );
7256 maybe_set_to_sigexit(SIGSEGV);
7257 maybe_set_to_sigexit(SIGTRAP);
7258 } /* else: hush is perfect. what SEGV? */
7259 maybe_set_to_sigexit(SIGABRT);
7260 /* bash 3.2 seems to handle these just like 'fatal' ones */
7261 maybe_set_to_sigexit(SIGPIPE);
7262 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007263 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007264 * if we aren't interactive... but in this case
7265 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007266 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007267 /*maybe_set_to_sigexit(SIGTERM);*/
7268 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007269}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007270#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007271
Denis Vlasenkod5762932009-03-31 11:22:57 +00007272static int set_mode(const char cstate, const char mode)
7273{
7274 int state = (cstate == '-' ? 1 : 0);
7275 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007276 case 'n': G.n_mode = state; break;
7277 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007278 default: return EXIT_FAILURE;
7279 }
7280 return EXIT_SUCCESS;
7281}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007282
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007283int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007284int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007285{
7286 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007287 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007288 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007289 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00007290
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007291 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007292 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007293 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007294#if !BB_MMU
7295 G.argv0_for_re_execing = argv[0];
7296#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007297 /* Deal with HUSH_VERSION */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007298 G.shell_ver.flg_export = 1;
7299 G.shell_ver.flg_read_only = 1;
7300 /* Code which handles ${var/P/R} needs writable values for all variables,
7301 * therefore we xstrdup: */
7302 G.shell_ver.varstr = xstrdup(hush_version_str),
Denis Vlasenko87a86552008-07-29 19:43:10 +00007303 G.top_var = &G.shell_ver;
Denys Vlasenko605067b2010-09-06 12:10:51 +02007304 /* Create shell local variables from the values
7305 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007306 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007307 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007308 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007309 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007310 if (e) while (*e) {
7311 char *value = strchr(*e, '=');
7312 if (value) { /* paranoia */
7313 cur_var->next = xzalloc(sizeof(*cur_var));
7314 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007315 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007316 cur_var->max_len = strlen(*e);
7317 cur_var->flg_export = 1;
7318 }
7319 e++;
7320 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007321 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7322 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7323 putenv(G.shell_ver.varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007324
7325 /* Export PWD */
7326 set_pwd_var(/*exp:*/ 1);
7327 /* bash also exports SHLVL and _,
7328 * and sets (but doesn't export) the following variables:
7329 * BASH=/bin/bash
7330 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7331 * BASH_VERSION='3.2.0(1)-release'
7332 * HOSTTYPE=i386
7333 * MACHTYPE=i386-pc-linux-gnu
7334 * OSTYPE=linux-gnu
7335 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007336 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007337 * EUID=<NNNNN>
7338 * UID=<NNNNN>
7339 * GROUPS=()
7340 * LINES=<NNN>
7341 * COLUMNS=<NNN>
7342 * BASH_ARGC=()
7343 * BASH_ARGV=()
7344 * BASH_LINENO=()
7345 * BASH_SOURCE=()
7346 * DIRSTACK=()
7347 * PIPESTATUS=([0]="0")
7348 * HISTFILE=/<xxx>/.bash_history
7349 * HISTFILESIZE=500
7350 * HISTSIZE=500
7351 * MAILCHECK=60
7352 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7353 * SHELL=/bin/bash
7354 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7355 * TERM=dumb
7356 * OPTERR=1
7357 * OPTIND=1
7358 * IFS=$' \t\n'
7359 * PS1='\s-\v\$ '
7360 * PS2='> '
7361 * PS4='+ '
7362 */
7363
Denis Vlasenko38f63192007-01-22 09:03:07 +00007364#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007365 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007366#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007367 G.global_argc = argc;
7368 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007369 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007370 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007371
Denis Vlasenkoed782372009-04-10 00:45:02 +00007372 if (setjmp(die_jmp)) {
7373 /* xfunc has failed! die die die */
7374 /* no EXIT traps, this is an escape hatch! */
7375 G.exiting = 1;
7376 hush_exit(xfunc_error_retval);
7377 }
7378
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007379 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007380 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007381 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007382 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007383 * in order to intercept (more) signals.
7384 */
7385
7386 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007387 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007388 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007389 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007390 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007391#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007392 "<:$:R:V:"
7393# if ENABLE_HUSH_FUNCTIONS
7394 "F:"
7395# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007396#endif
7397 );
7398 if (opt <= 0)
7399 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007400 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007401 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007402 /* Possibilities:
7403 * sh ... -c 'script'
7404 * sh ... -c 'script' ARG0 [ARG1...]
7405 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007406 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007407 * "" needs to be replaced with NULL
7408 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007409 * Note: the form without ARG0 never happens:
7410 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007411 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007412 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007413 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007414 G.root_ppid = getppid();
7415 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007416 G.global_argv = argv + optind;
7417 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007418 if (builtin_argc) {
7419 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7420 const struct built_in_command *x;
7421
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007422 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007423 x = find_builtin(optarg);
7424 if (x) { /* paranoia */
7425 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7426 G.global_argv += builtin_argc;
7427 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007428 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007429 }
7430 goto final_return;
7431 }
7432 if (!G.global_argv[0]) {
7433 /* -c 'script' (no params): prevent empty $0 */
7434 G.global_argv--; /* points to argv[i] of 'script' */
7435 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007436 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007437 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007438 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007439 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007440 goto final_return;
7441 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007442 /* Well, we cannot just declare interactiveness,
7443 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007444 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007445 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007446 case 's':
7447 /* "-s" means "read from stdin", but this is how we always
7448 * operate, so simply do nothing here. */
7449 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007450#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007451 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007452 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007453 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007454 case '$': {
7455 unsigned long long empty_trap_mask;
7456
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007457 G.root_pid = bb_strtou(optarg, &optarg, 16);
7458 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007459 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7460 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007461 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7462 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007463 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007464 optarg++;
7465 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007466 optarg++;
7467 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7468 if (empty_trap_mask != 0) {
7469 int sig;
7470 init_sigmasks();
7471 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7472 for (sig = 1; sig < NSIG; sig++) {
7473 if (empty_trap_mask & (1LL << sig)) {
7474 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7475 sigaddset(&G.blocked_set, sig);
7476 }
7477 }
7478 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7479 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007480# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007481 optarg++;
7482 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007483# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007484 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007485 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007486 case 'R':
7487 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007488 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007489 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007490# if ENABLE_HUSH_FUNCTIONS
7491 case 'F': {
7492 struct function *funcp = new_function(optarg);
7493 /* funcp->name is already set to optarg */
7494 /* funcp->body is set to NULL. It's a special case. */
7495 funcp->body_as_string = argv[optind];
7496 optind++;
7497 break;
7498 }
7499# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007500#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007501 case 'n':
7502 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007503 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007504 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007505 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007506#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007507 fprintf(stderr, "Usage: sh [FILE]...\n"
7508 " or: sh -c command [args]...\n\n");
7509 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007510#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007511 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007512#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007513 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007514 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007515
Denys Vlasenkodea47882009-10-09 15:40:49 +02007516 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007517 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007518 G.root_ppid = getppid();
7519 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007520
7521 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007522 if (argv[0] && argv[0][0] == '-') {
7523 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007524 debug_printf("sourcing /etc/profile\n");
7525 input = fopen_for_read("/etc/profile");
7526 if (input != NULL) {
7527 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007528 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007529 parse_and_run_file(input);
7530 fclose(input);
7531 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007532 /* bash: after sourcing /etc/profile,
7533 * tries to source (in the given order):
7534 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007535 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007536 * bash also sources ~/.bash_logout on exit.
7537 * If called as sh, skips .bash_XXX files.
7538 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007539 }
7540
Denis Vlasenkof9375282009-04-05 19:13:39 +00007541 if (argv[optind]) {
7542 FILE *input;
7543 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007544 * "bash <script>" (which is never interactive (unless -i?))
7545 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007546 * If called as sh, does the same but with $ENV.
7547 */
7548 debug_printf("running script '%s'\n", argv[optind]);
7549 G.global_argv = argv + optind;
7550 G.global_argc = argc - optind;
7551 input = xfopen_for_read(argv[optind]);
7552 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007553 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007554 parse_and_run_file(input);
7555#if ENABLE_FEATURE_CLEAN_UP
7556 fclose(input);
7557#endif
7558 goto final_return;
7559 }
7560
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007561 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007562 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007563 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007564
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007565 /* A shell is interactive if the '-i' flag was given,
7566 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007567 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007568 * no arguments remaining or the -s flag given
7569 * standard input is a terminal
7570 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007571 * Refer to Posix.2, the description of the 'sh' utility.
7572 */
7573#if ENABLE_HUSH_JOB
7574 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007575 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7576 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7577 if (G_saved_tty_pgrp < 0)
7578 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007579
7580 /* try to dup stdin to high fd#, >= 255 */
7581 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7582 if (G_interactive_fd < 0) {
7583 /* try to dup to any fd */
7584 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007585 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007586 /* give up */
7587 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007588 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007589 }
7590 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007591// TODO: track & disallow any attempts of user
7592// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007593 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007594 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007595 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007596 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007597
Mike Frysinger38478a62009-05-20 04:48:06 -04007598 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007599 /* If we were run as 'hush &', sleep until we are
7600 * in the foreground (tty pgrp == our pgrp).
7601 * If we get started under a job aware app (like bash),
7602 * make sure we are now in charge so we don't fight over
7603 * who gets the foreground */
7604 while (1) {
7605 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007606 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7607 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007608 break;
7609 /* send TTIN to ourself (should stop us) */
7610 kill(- shell_pgrp, SIGTTIN);
7611 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007612 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007613
Denis Vlasenkof9375282009-04-05 19:13:39 +00007614 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007615 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007616
Mike Frysinger38478a62009-05-20 04:48:06 -04007617 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007618 /* Set other signals to restore saved_tty_pgrp */
7619 set_fatal_handlers();
7620 /* Put ourselves in our own process group
7621 * (bash, too, does this only if ctty is available) */
7622 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7623 /* Grab control of the terminal */
7624 tcsetpgrp(G_interactive_fd, getpid());
7625 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007626 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007627 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007628 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007629 } else {
7630 init_sigmasks();
7631 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007632#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007633 /* No job control compiled in, only prompt/line editing */
7634 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007635 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7636 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007637 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007638 G_interactive_fd = dup(STDIN_FILENO);
7639 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007640 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007641 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007642 }
7643 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007644 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007645 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007646 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007647 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007648#else
7649 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007650 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007651#endif
7652 /* bash:
7653 * if interactive but not a login shell, sources ~/.bashrc
7654 * (--norc turns this off, --rcfile <file> overrides)
7655 */
7656
7657 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007658 /* note: ash and hush share this string */
7659 printf("\n\n%s %s\n"
7660 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7661 "\n",
7662 bb_banner,
7663 "hush - the humble shell"
7664 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007665 }
7666
Denis Vlasenkof9375282009-04-05 19:13:39 +00007667 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007668
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007669 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007670#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007671 if (G.cwd != bb_msg_unknown)
7672 free((char*)G.cwd);
7673 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007674 while (cur_var) {
7675 struct variable *tmp = cur_var;
7676 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007677 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007678 cur_var = cur_var->next;
7679 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007680 }
Eric Andersen25f27032001-04-26 23:22:31 +00007681#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007682 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007683}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007684
7685
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007686#if ENABLE_MSH
7687int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7688int msh_main(int argc, char **argv)
7689{
7690 //bb_error_msg("msh is deprecated, please use hush instead");
7691 return hush_main(argc, argv);
7692}
7693#endif
7694
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007695
7696/*
7697 * Built-ins
7698 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007699static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007700{
7701 return 0;
7702}
7703
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007704static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007705{
7706 int argc = 0;
7707 while (*argv) {
7708 argc++;
7709 argv++;
7710 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007711 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007712}
7713
7714static int FAST_FUNC builtin_test(char **argv)
7715{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007716 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007717}
7718
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007719static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007720{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007721 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007722}
7723
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007724#if ENABLE_PRINTF
7725static int FAST_FUNC builtin_printf(char **argv)
7726{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007727 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007728}
7729#endif
7730
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007731static char **skip_dash_dash(char **argv)
7732{
7733 argv++;
7734 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7735 argv++;
7736 return argv;
7737}
7738
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007739static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007740{
7741 int rcode = EXIT_SUCCESS;
7742
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007743 argv = skip_dash_dash(argv);
7744 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007745 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007746 /* bash:
7747 * eval "echo Hi; done" ("done" is syntax error):
7748 * "echo Hi" will not execute too.
7749 */
7750 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007751 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007752 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007753 }
7754 return rcode;
7755}
7756
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007757static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007758{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007759 const char *newdir;
7760
7761 argv = skip_dash_dash(argv);
7762 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007763 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007764 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007765 * bash says "bash: cd: HOME not set" and does nothing
7766 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007767 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007768 const char *home = get_local_var_value("HOME");
7769 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007770 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007771 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007772 /* Mimic bash message exactly */
7773 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007774 return EXIT_FAILURE;
7775 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007776 /* Read current dir (get_cwd(1) is inside) and set PWD.
7777 * Note: do not enforce exporting. If PWD was unset or unexported,
7778 * set it again, but do not export. bash does the same.
7779 */
7780 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007781 return EXIT_SUCCESS;
7782}
7783
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007784static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007785{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007786 argv = skip_dash_dash(argv);
7787 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007788 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007789
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007790 /* Careful: we can end up here after [v]fork. Do not restore
7791 * tty pgrp then, only top-level shell process does that */
7792 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7793 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7794
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007795 /* TODO: if exec fails, bash does NOT exit! We do.
7796 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7797 * and tcsetpgrp, and this is inherently racy.
7798 */
7799 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007800}
7801
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007802static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007803{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007804 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007805
7806 /* interactive bash:
7807 * # trap "echo EEE" EXIT
7808 * # exit
7809 * exit
7810 * There are stopped jobs.
7811 * (if there are _stopped_ jobs, running ones don't count)
7812 * # exit
7813 * exit
7814 # EEE (then bash exits)
7815 *
7816 * we can use G.exiting = -1 as indicator "last cmd was exit"
7817 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007818
7819 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007820 argv = skip_dash_dash(argv);
7821 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007822 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007823 /* mimic bash: exit 123abc == exit 255 + error msg */
7824 xfunc_error_retval = 255;
7825 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007826 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007827}
7828
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007829static void print_escaped(const char *s)
7830{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007831 if (*s == '\'')
7832 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007833 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007834 const char *p = strchrnul(s, '\'');
7835 /* print 'xxxx', possibly just '' */
7836 printf("'%.*s'", (int)(p - s), s);
7837 if (*p == '\0')
7838 break;
7839 s = p;
7840 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007841 /* s points to '; print "'''...'''" */
7842 putchar('"');
7843 do putchar('\''); while (*++s == '\'');
7844 putchar('"');
7845 } while (*s);
7846}
7847
Denys Vlasenko295fef82009-06-03 12:47:26 +02007848#if !ENABLE_HUSH_LOCAL
7849#define helper_export_local(argv, exp, lvl) \
7850 helper_export_local(argv, exp)
7851#endif
7852static void helper_export_local(char **argv, int exp, int lvl)
7853{
7854 do {
7855 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007856 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02007857
7858 /* So far we do not check that name is valid (TODO?) */
7859
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007860 if (*name_end == '\0') {
7861 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02007862
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007863 vpp = get_ptr_to_local_var(name, name_end - name);
7864 var = vpp ? *vpp : NULL;
7865
Denys Vlasenko295fef82009-06-03 12:47:26 +02007866 if (exp == -1) { /* unexporting? */
7867 /* export -n NAME (without =VALUE) */
7868 if (var) {
7869 var->flg_export = 0;
7870 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7871 unsetenv(name);
7872 } /* else: export -n NOT_EXISTING_VAR: no-op */
7873 continue;
7874 }
7875 if (exp == 1) { /* exporting? */
7876 /* export NAME (without =VALUE) */
7877 if (var) {
7878 var->flg_export = 1;
7879 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7880 putenv(var->varstr);
7881 continue;
7882 }
7883 }
7884 /* Exporting non-existing variable.
7885 * bash does not put it in environment,
7886 * but remembers that it is exported,
7887 * and does put it in env when it is set later.
7888 * We just set it to "" and export. */
7889 /* Or, it's "local NAME" (without =VALUE).
7890 * bash sets the value to "". */
7891 name = xasprintf("%s=", name);
7892 } else {
7893 /* (Un)exporting/making local NAME=VALUE */
7894 name = xstrdup(name);
7895 }
7896 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7897 } while (*++argv);
7898}
7899
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007900static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007901{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007902 unsigned opt_unexport;
7903
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007904#if ENABLE_HUSH_EXPORT_N
7905 /* "!": do not abort on errors */
7906 opt_unexport = getopt32(argv, "!n");
7907 if (opt_unexport == (uint32_t)-1)
7908 return EXIT_FAILURE;
7909 argv += optind;
7910#else
7911 opt_unexport = 0;
7912 argv++;
7913#endif
7914
7915 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007916 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007917 if (e) {
7918 while (*e) {
7919#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007920 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007921#else
7922 /* ash emits: export VAR='VAL'
7923 * bash: declare -x VAR="VAL"
7924 * we follow ash example */
7925 const char *s = *e++;
7926 const char *p = strchr(s, '=');
7927
7928 if (!p) /* wtf? take next variable */
7929 continue;
7930 /* export var= */
7931 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007932 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007933 putchar('\n');
7934#endif
7935 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007936 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007937 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007938 return EXIT_SUCCESS;
7939 }
7940
Denys Vlasenko295fef82009-06-03 12:47:26 +02007941 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007942
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007943 return EXIT_SUCCESS;
7944}
7945
Denys Vlasenko295fef82009-06-03 12:47:26 +02007946#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007947static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007948{
7949 if (G.func_nest_level == 0) {
7950 bb_error_msg("%s: not in a function", argv[0]);
7951 return EXIT_FAILURE; /* bash compat */
7952 }
7953 helper_export_local(argv, 0, G.func_nest_level);
7954 return EXIT_SUCCESS;
7955}
7956#endif
7957
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007958static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007959{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007960 int sig;
7961 char *new_cmd;
7962
7963 if (!G.traps)
7964 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7965
7966 argv++;
7967 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007968 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007969 /* No args: print all trapped */
7970 for (i = 0; i < NSIG; ++i) {
7971 if (G.traps[i]) {
7972 printf("trap -- ");
7973 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007974 /* note: bash adds "SIG", but only if invoked
7975 * as "bash". If called as "sh", or if set -o posix,
7976 * then it prints short signal names.
7977 * We are printing short names: */
7978 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007979 }
7980 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007981 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007982 return EXIT_SUCCESS;
7983 }
7984
7985 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007986 /* If first arg is a number: reset all specified signals */
7987 sig = bb_strtou(*argv, NULL, 10);
7988 if (errno == 0) {
7989 int ret;
7990 process_sig_list:
7991 ret = EXIT_SUCCESS;
7992 while (*argv) {
7993 sig = get_signum(*argv++);
7994 if (sig < 0 || sig >= NSIG) {
7995 ret = EXIT_FAILURE;
7996 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007997 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007998 continue;
7999 }
8000
8001 free(G.traps[sig]);
8002 G.traps[sig] = xstrdup(new_cmd);
8003
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008004 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008005 get_signame(sig), sig, G.traps[sig]);
8006
8007 /* There is no signal for 0 (EXIT) */
8008 if (sig == 0)
8009 continue;
8010
8011 if (new_cmd) {
8012 sigaddset(&G.blocked_set, sig);
8013 } else {
8014 /* There was a trap handler, we are removing it
8015 * (if sig has non-DFL handling,
8016 * we don't need to do anything) */
8017 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8018 continue;
8019 sigdelset(&G.blocked_set, sig);
8020 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008021 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008022 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008023 return ret;
8024 }
8025
8026 if (!argv[1]) { /* no second arg */
8027 bb_error_msg("trap: invalid arguments");
8028 return EXIT_FAILURE;
8029 }
8030
8031 /* First arg is "-": reset all specified to default */
8032 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8033 /* Everything else: set arg as signal handler
8034 * (includes "" case, which ignores signal) */
8035 if (argv[0][0] == '-') {
8036 if (argv[0][1] == '\0') { /* "-" */
8037 /* new_cmd remains NULL: "reset these sigs" */
8038 goto reset_traps;
8039 }
8040 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8041 argv++;
8042 }
8043 /* else: "-something", no special meaning */
8044 }
8045 new_cmd = *argv;
8046 reset_traps:
8047 argv++;
8048 goto process_sig_list;
8049}
8050
Mike Frysinger93cadc22009-05-27 17:06:25 -04008051/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008052static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008053{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008054 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008055
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008056 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008057 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008058 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008059
8060 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008061 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008062 type = "an alias";*/
8063#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008064 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008065 type = "a function";
8066#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008067 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008068 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008069 else if ((path = find_in_path(*argv)) != NULL)
8070 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008071 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008072 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008073 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008074 continue;
8075 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008076
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008077 printf("%s is %s\n", *argv, type);
8078 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008079 }
8080
8081 return ret;
8082}
8083
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008084#if ENABLE_HUSH_JOB
8085/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008086static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008087{
8088 int i, jobnum;
8089 struct pipe *pi;
8090
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008091 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008092 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008093
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008094 /* If they gave us no args, assume they want the last backgrounded task */
8095 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008096 for (pi = G.job_list; pi; pi = pi->next) {
8097 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008098 goto found;
8099 }
8100 }
8101 bb_error_msg("%s: no current job", argv[0]);
8102 return EXIT_FAILURE;
8103 }
8104 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8105 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8106 return EXIT_FAILURE;
8107 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008108 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008109 if (pi->jobid == jobnum) {
8110 goto found;
8111 }
8112 }
8113 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8114 return EXIT_FAILURE;
8115 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008116 /* TODO: bash prints a string representation
8117 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008118 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008119 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008120 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008121 }
8122
8123 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008124 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8125 for (i = 0; i < pi->num_cmds; i++) {
8126 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8127 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008128 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008129 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008130
8131 i = kill(- pi->pgrp, SIGCONT);
8132 if (i < 0) {
8133 if (errno == ESRCH) {
8134 delete_finished_bg_job(pi);
8135 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008136 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008137 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008138 }
8139
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008140 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008141 remove_bg_job(pi);
8142 return checkjobs_and_fg_shell(pi);
8143 }
8144 return EXIT_SUCCESS;
8145}
8146#endif
8147
8148#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008149static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008150{
8151 const struct built_in_command *x;
8152
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008153 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008154 "Built-in commands:\n"
8155 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008156 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008157 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008158 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008159 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008160 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008161 return EXIT_SUCCESS;
8162}
8163#endif
8164
8165#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008166static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008167{
8168 struct pipe *job;
8169 const char *status_string;
8170
Denis Vlasenko87a86552008-07-29 19:43:10 +00008171 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008172 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008173 status_string = "Stopped";
8174 else
8175 status_string = "Running";
8176
8177 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8178 }
8179 return EXIT_SUCCESS;
8180}
8181#endif
8182
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008183#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008184static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008185{
8186 void *p;
8187 unsigned long l;
8188
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008189# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008190 /* Optional. Reduces probability of false positives */
8191 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008192# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008193 /* Crude attempt to find where "free memory" starts,
8194 * sans fragmentation. */
8195 p = malloc(240);
8196 l = (unsigned long)p;
8197 free(p);
8198 p = malloc(3400);
8199 if (l < (unsigned long)p) l = (unsigned long)p;
8200 free(p);
8201
8202 if (!G.memleak_value)
8203 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008204
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008205 l -= G.memleak_value;
8206 if ((long)l < 0)
8207 l = 0;
8208 l /= 1024;
8209 if (l > 127)
8210 l = 127;
8211
8212 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8213 return l;
8214}
8215#endif
8216
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008217static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008218{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008219 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008220 return EXIT_SUCCESS;
8221}
8222
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008223static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008224{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008225 const char *r;
8226 char *opt_n = NULL;
8227 char *opt_p = NULL;
8228 char *opt_t = NULL;
8229 char *opt_u = NULL;
8230 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008231
Denys Vlasenko03dad222010-01-12 23:29:57 +01008232 /* "!": do not abort on errors.
8233 * Option string must start with "sr" to match BUILTIN_READ_xxx
8234 */
8235 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8236 if (read_flags == (uint32_t)-1)
8237 return EXIT_FAILURE;
8238 argv += optind;
8239
8240 r = shell_builtin_read(set_local_var_from_halves,
8241 argv,
8242 get_local_var_value("IFS"), /* can be NULL */
8243 read_flags,
8244 opt_n,
8245 opt_p,
8246 opt_t,
8247 opt_u
8248 );
8249
8250 if ((uintptr_t)r > 1) {
8251 bb_error_msg("%s", r);
8252 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008253 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008254
Denys Vlasenko03dad222010-01-12 23:29:57 +01008255 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008256}
8257
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008258/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8259 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008260 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008261 * set [-abCefhmnuvx] [-o option] [argument...]
8262 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008263 * set -- [argument...]
8264 * set -o
8265 * set +o
8266 * Implementations shall support the options in both their hyphen and
8267 * plus-sign forms. These options can also be specified as options to sh.
8268 * Examples:
8269 * Write out all variables and their values: set
8270 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8271 * Turn on the -x and -v options: set -xv
8272 * Unset all positional parameters: set --
8273 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8274 * Set the positional parameters to the expansion of x, even if x expands
8275 * with a leading '-' or '+': set -- $x
8276 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008277 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008278 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008279static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008280{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008281 int n;
8282 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008283 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008284
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008285 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008286 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008287 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008288 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008289 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008290 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008291
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008292 do {
8293 if (!strcmp(arg, "--")) {
8294 ++argv;
8295 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008296 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008297 if (arg[0] != '+' && arg[0] != '-')
8298 break;
8299 for (n = 1; arg[n]; ++n)
8300 if (set_mode(arg[0], arg[n]))
8301 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008302 } while ((arg = *++argv) != NULL);
8303 /* Now argv[0] is 1st argument */
8304
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008305 if (arg == NULL)
8306 return EXIT_SUCCESS;
8307 set_argv:
8308
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008309 /* NB: G.global_argv[0] ($0) is never freed/changed */
8310 g_argv = G.global_argv;
8311 if (G.global_args_malloced) {
8312 pp = g_argv;
8313 while (*++pp)
8314 free(*pp);
8315 g_argv[1] = NULL;
8316 } else {
8317 G.global_args_malloced = 1;
8318 pp = xzalloc(sizeof(pp[0]) * 2);
8319 pp[0] = g_argv[0]; /* retain $0 */
8320 g_argv = pp;
8321 }
8322 /* This realloc's G.global_argv */
8323 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8324
8325 n = 1;
8326 while (*++pp)
8327 n++;
8328 G.global_argc = n;
8329
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008330 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008331
8332 /* Nothing known, so abort */
8333 error:
8334 bb_error_msg("set: %s: invalid option", arg);
8335 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008336}
8337
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008338static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008339{
8340 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008341 argv = skip_dash_dash(argv);
8342 if (argv[0]) {
8343 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008344 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008345 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008346 if (G.global_args_malloced) {
8347 int m = 1;
8348 while (m <= n)
8349 free(G.global_argv[m++]);
8350 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008351 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008352 memmove(&G.global_argv[1], &G.global_argv[n+1],
8353 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008354 return EXIT_SUCCESS;
8355 }
8356 return EXIT_FAILURE;
8357}
8358
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008359static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008360{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008361 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008362 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008363 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008364#if ENABLE_HUSH_FUNCTIONS
8365 smallint sv_flg;
8366#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008367
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008368 argv = skip_dash_dash(argv);
8369 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008370 if (!filename) {
8371 /* bash says: "bash: .: filename argument required" */
8372 return 2; /* bash compat */
8373 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008374 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008375 if (!strchr(filename, '/')) {
8376 arg_path = find_in_path(filename);
8377 if (arg_path)
8378 filename = arg_path;
8379 }
8380 input = fopen_or_warn(filename, "r");
8381 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008382 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008383 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008384 return EXIT_FAILURE;
8385 }
8386 close_on_exec_on(fileno(input));
8387
Mike Frysinger885b6f22009-04-18 21:04:25 +00008388#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008389 sv_flg = G.flag_return_in_progress;
8390 /* "we are inside sourced file, ok to use return" */
8391 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008392#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008393 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008394
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008395 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008396 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008397
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008398 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008399#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008400 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008401#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008402
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008403 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008404}
8405
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008406static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008407{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008408 int rc;
8409 mode_t mask;
8410
8411 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008412 argv = skip_dash_dash(argv);
8413 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008414 mode_t old_mask = mask;
8415
8416 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008417 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008418 mask ^= 0777;
8419 if (rc == 0) {
8420 mask = old_mask;
8421 /* bash messages:
8422 * bash: umask: 'q': invalid symbolic mode operator
8423 * bash: umask: 999: octal number out of range
8424 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008425 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008426 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008427 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008428 rc = 1;
8429 /* Mimic bash */
8430 printf("%04o\n", (unsigned) mask);
8431 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008432 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008433 umask(mask);
8434
8435 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008436}
8437
Mike Frysingerd690f682009-03-30 06:50:54 +00008438/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008439static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008440{
Mike Frysingerd690f682009-03-30 06:50:54 +00008441 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008442 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008443
Denis Vlasenko28e67962009-04-26 23:22:40 +00008444 /* "!": do not abort on errors */
8445 /* "+": stop at 1st non-option */
8446 opts = getopt32(argv, "!+vf");
8447 if (opts == (unsigned)-1)
8448 return EXIT_FAILURE;
8449 if (opts == 3) {
8450 bb_error_msg("unset: -v and -f are exclusive");
8451 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008452 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008453 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008454
8455 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008456 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008457 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008458 if (unset_local_var(*argv)) {
8459 /* unset <nonexistent_var> doesn't fail.
8460 * Error is when one tries to unset RO var.
8461 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008462 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008463 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008464 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008465#if ENABLE_HUSH_FUNCTIONS
8466 else {
8467 unset_func(*argv);
8468 }
8469#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008470 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008471 }
8472 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008473}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008474
Mike Frysinger56bdea12009-03-28 20:01:58 +00008475/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008476static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008477{
8478 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008479 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008480
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008481 argv = skip_dash_dash(argv);
8482 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008483 /* Don't care about wait results */
8484 /* Note 1: must wait until there are no more children */
8485 /* Note 2: must be interruptible */
8486 /* Examples:
8487 * $ sleep 3 & sleep 6 & wait
8488 * [1] 30934 sleep 3
8489 * [2] 30935 sleep 6
8490 * [1] Done sleep 3
8491 * [2] Done sleep 6
8492 * $ sleep 3 & sleep 6 & wait
8493 * [1] 30936 sleep 3
8494 * [2] 30937 sleep 6
8495 * [1] Done sleep 3
8496 * ^C <-- after ~4 sec from keyboard
8497 * $
8498 */
8499 sigaddset(&G.blocked_set, SIGCHLD);
8500 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8501 while (1) {
8502 checkjobs(NULL);
8503 if (errno == ECHILD)
8504 break;
8505 /* Wait for SIGCHLD or any other signal of interest */
8506 /* sigtimedwait with infinite timeout: */
8507 sig = sigwaitinfo(&G.blocked_set, NULL);
8508 if (sig > 0) {
8509 sig = check_and_run_traps(sig);
8510 if (sig && sig != SIGCHLD) { /* see note 2 */
8511 ret = 128 + sig;
8512 break;
8513 }
8514 }
8515 }
8516 sigdelset(&G.blocked_set, SIGCHLD);
8517 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8518 return ret;
8519 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008520
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008521 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008522 while (*argv) {
8523 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008524 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008525 /* mimic bash message */
8526 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008527 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008528 }
8529 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008530 if (WIFSIGNALED(status))
8531 ret = 128 + WTERMSIG(status);
8532 else if (WIFEXITED(status))
8533 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008534 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008535 ret = EXIT_FAILURE;
8536 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008537 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008538 ret = 127;
8539 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008540 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008541 }
8542
8543 return ret;
8544}
8545
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008546#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8547static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8548{
8549 if (argv[1]) {
8550 def = bb_strtou(argv[1], NULL, 10);
8551 if (errno || def < def_min || argv[2]) {
8552 bb_error_msg("%s: bad arguments", argv[0]);
8553 def = UINT_MAX;
8554 }
8555 }
8556 return def;
8557}
8558#endif
8559
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008560#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008561static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008562{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008563 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008564 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008565 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008566 return EXIT_SUCCESS; /* bash compat */
8567 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008568 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008569
8570 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8571 if (depth == UINT_MAX)
8572 G.flag_break_continue = BC_BREAK;
8573 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008574 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008575
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008576 return EXIT_SUCCESS;
8577}
8578
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008579static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008580{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008581 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8582 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008583}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008584#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008585
8586#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008587static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008588{
8589 int rc;
8590
8591 if (G.flag_return_in_progress != -1) {
8592 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8593 return EXIT_FAILURE; /* bash compat */
8594 }
8595
8596 G.flag_return_in_progress = 1;
8597
8598 /* bash:
8599 * out of range: wraps around at 256, does not error out
8600 * non-numeric param:
8601 * f() { false; return qwe; }; f; echo $?
8602 * bash: return: qwe: numeric argument required <== we do this
8603 * 255 <== we also do this
8604 */
8605 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8606 return rc;
8607}
8608#endif