blob: ae2876ac71cddbe0064538c87d1b6d9e91bf258b [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
Mike Frysinger98c52642009-04-02 10:02:37 +00001674#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko8391c482010-05-22 17:50:43 +02001675# define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1676# define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denys Vlasenko03dad222010-01-12 23:29:57 +01001677static char* FAST_FUNC endofname(const char *name)
Mike Frysinger98c52642009-04-02 10:02:37 +00001678{
1679 char *p;
1680
1681 p = (char *) name;
1682 if (!is_name(*p))
1683 return p;
1684 while (*++p) {
1685 if (!is_in_name(*p))
1686 break;
1687 }
1688 return p;
1689}
Denys Vlasenko6b01b712010-01-24 22:52:21 +01001690#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001691
Denys Vlasenko03dad222010-01-12 23:29:57 +01001692static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001693{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001694 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001695 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001696}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001697
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001698
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001699/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001700 * Helpers for "var1=val1 var2=val2 cmd" feature
1701 */
1702static void add_vars(struct variable *var)
1703{
1704 struct variable *next;
1705
1706 while (var) {
1707 next = var->next;
1708 var->next = G.top_var;
1709 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001710 if (var->flg_export) {
1711 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001712 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001713 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001714 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001715 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001716 var = next;
1717 }
1718}
1719
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001720static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001721{
1722 char **s;
1723 struct variable *old = NULL;
1724
1725 if (!strings)
1726 return old;
1727 s = strings;
1728 while (*s) {
1729 struct variable *var_p;
1730 struct variable **var_pp;
1731 char *eq;
1732
1733 eq = strchr(*s, '=');
1734 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001735 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001736 if (var_pp) {
1737 /* Remove variable from global linked list */
1738 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001739 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001740 *var_pp = var_p->next;
1741 /* Add it to returned list */
1742 var_p->next = old;
1743 old = var_p;
1744 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001745 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001746 }
1747 s++;
1748 }
1749 return old;
1750}
1751
1752
1753/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001754 * in_str support
1755 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001756static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001757{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001758 int ch = *i->p;
1759 if (ch != '\0') {
1760 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001761 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001762 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001763 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001764}
1765
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001766static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001767{
1768 return *i->p;
1769}
1770
1771#if ENABLE_HUSH_INTERACTIVE
1772
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001773static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001774{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001775 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001776 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001777 if (G.PS1 == NULL)
1778 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001779 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001780 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001781 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001782 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001783 if (G.PS2 == NULL)
1784 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001785}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001786
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001787static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001788{
1789 const char *prompt_str;
1790 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001791 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1792 /* Set up the prompt */
1793 if (promptmode == 0) { /* PS1 */
1794 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001795 /* bash uses $PWD value, even if it is set by user.
1796 * It uses current dir only if PWD is unset.
1797 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001798 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001799 prompt_str = G.PS1;
1800 } else
1801 prompt_str = G.PS2;
1802 } else
1803 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001804 debug_printf("result '%s'\n", prompt_str);
1805 return prompt_str;
1806}
1807
1808static void get_user_input(struct in_str *i)
1809{
1810 int r;
1811 const char *prompt_str;
1812
1813 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001814# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001815 /* Enable command line editing only while a command line
1816 * is actually being read */
1817 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001818 G.flag_SIGINT = 0;
1819 /* buglet: SIGINT will not make new prompt to appear _at once_,
1820 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001821 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 +00001822 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001823 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001824 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001825 i->eof_flag = (r < 0);
1826 if (i->eof_flag) { /* EOF/error detected */
1827 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1828 G.user_input_buf[1] = '\0';
1829 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001830# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001831 do {
1832 G.flag_SIGINT = 0;
1833 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001834 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001835 G.user_input_buf[0] = r = fgetc(i->file);
1836 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001837//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001838 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001839 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001840# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001841 i->p = G.user_input_buf;
1842}
1843
1844#endif /* INTERACTIVE */
1845
1846/* This is the magic location that prints prompts
1847 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001848static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001849{
1850 int ch;
1851
1852 /* If there is data waiting, eat it up */
1853 if (i->p && *i->p) {
1854#if ENABLE_HUSH_INTERACTIVE
1855 take_cached:
1856#endif
1857 ch = *i->p++;
1858 if (i->eof_flag && !*i->p)
1859 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001860 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001861 } else {
1862 /* need to double check i->file because we might be doing something
1863 * more complicated by now, like sourcing or substituting. */
1864#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001865 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001866 do {
1867 get_user_input(i);
1868 } while (!*i->p); /* need non-empty line */
1869 i->promptmode = 1; /* PS2 */
1870 i->promptme = 0;
1871 goto take_cached;
1872 }
1873#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001874 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001875 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001876 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001877#if ENABLE_HUSH_INTERACTIVE
1878 if (ch == '\n')
1879 i->promptme = 1;
1880#endif
1881 return ch;
1882}
1883
Denis Vlasenko913a2012009-04-05 22:17:04 +00001884/* All callers guarantee this routine will never
1885 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001886 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001887static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001888{
1889 int ch;
1890 if (i->p && *i->p) {
1891 if (i->eof_flag && !i->p[1])
1892 return EOF;
1893 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001894 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001895 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001896 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001897 i->eof_flag = (ch == EOF);
1898 i->peek_buf[0] = ch;
1899 i->peek_buf[1] = '\0';
1900 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001901 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001902 return ch;
1903}
1904
1905static void setup_file_in_str(struct in_str *i, FILE *f)
1906{
1907 i->peek = file_peek;
1908 i->get = file_get;
1909#if ENABLE_HUSH_INTERACTIVE
1910 i->promptme = 1;
1911 i->promptmode = 0; /* PS1 */
1912#endif
1913 i->file = f;
1914 i->p = NULL;
1915}
1916
1917static void setup_string_in_str(struct in_str *i, const char *s)
1918{
1919 i->peek = static_peek;
1920 i->get = static_get;
1921#if ENABLE_HUSH_INTERACTIVE
1922 i->promptme = 1;
1923 i->promptmode = 0; /* PS1 */
1924#endif
1925 i->p = s;
1926 i->eof_flag = 0;
1927}
1928
1929
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001930/*
1931 * o_string support
1932 */
1933#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001934
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001935static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001936{
1937 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02001938 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001939 if (o->data)
1940 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001941}
1942
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001943static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001944{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001945 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001946 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001947}
1948
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001949static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1950{
1951 free(o->data);
1952}
1953
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001954static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001955{
1956 if (o->length + len > o->maxlen) {
1957 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1958 o->data = xrealloc(o->data, 1 + o->maxlen);
1959 }
1960}
1961
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001962static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001963{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001964 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1965 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001966 o->data[o->length] = ch;
1967 o->length++;
1968 o->data[o->length] = '\0';
1969}
1970
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001971static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001972{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001973 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001974 memcpy(&o->data[o->length], str, len);
1975 o->length += len;
1976 o->data[o->length] = '\0';
1977}
1978
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001979static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001980{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001981 o_addblock(o, str, strlen(str));
1982}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02001983
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001984#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001985static void nommu_addchr(o_string *o, int ch)
1986{
1987 if (o)
1988 o_addchr(o, ch);
1989}
1990#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001991# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001992#endif
1993
1994static void o_addstr_with_NUL(o_string *o, const char *str)
1995{
1996 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001997}
1998
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001999static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00002000{
2001 while (len) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002002 len--;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002003 o_addchr(o, *str);
2004 if (*str++ == '\\') {
2005 /* \z -> \\\z; \<eol> -> \\<eol> */
2006 o_addchr(o, '\\');
2007 if (len) {
2008 len--;
2009 o_addchr(o, '\\');
2010 o_addchr(o, *str++);
2011 }
2012 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002013 }
2014}
2015
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002016#undef HUSH_BRACE_EXP
2017/*
2018 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2019 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2020 * Apparently, on unquoted $v bash still does globbing
2021 * ("v='*.txt'; echo $v" prints all .txt files),
2022 * but NOT brace expansion! Thus, there should be TWO independent
2023 * quoting mechanisms on $v expansion side: one protects
2024 * $v from brace expansion, and other additionally protects "$v" against globbing.
2025 * We have only second one.
2026 */
2027
2028#ifdef HUSH_BRACE_EXP
2029# define MAYBE_BRACES "{}"
2030#else
2031# define MAYBE_BRACES ""
2032#endif
2033
Eric Andersen25f27032001-04-26 23:22:31 +00002034/* My analysis of quoting semantics tells me that state information
2035 * is associated with a destination, not a source.
2036 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002037static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002038{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002039 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002040 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002041 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002042 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002043 o_grow_by(o, sz);
2044 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002045 o->data[o->length] = '\\';
2046 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002047 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002048 o->data[o->length] = ch;
2049 o->length++;
2050 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002051}
2052
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002053static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002054{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002055 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002056 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002057 sz++;
2058 o->data[o->length] = '\\';
2059 o->length++;
2060 }
2061 o_grow_by(o, sz);
2062 o->data[o->length] = ch;
2063 o->length++;
2064 o->data[o->length] = '\0';
2065}
2066
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002067static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002068{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002069 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002070 char ch;
2071 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002072 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002073 if (ordinary_cnt > len) /* paranoia */
2074 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002075 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002076 if (ordinary_cnt == len)
2077 return;
2078 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002079 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002080
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002081 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002082 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002083 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002084 sz++;
2085 o->data[o->length] = '\\';
2086 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002087 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002088 o_grow_by(o, sz);
2089 o->data[o->length] = ch;
2090 o->length++;
2091 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002092 }
2093}
2094
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002095static void o_addQblock(o_string *o, const char *str, int len)
2096{
2097 if (!o->o_escape) {
2098 o_addblock(o, str, len);
2099 return;
2100 }
2101 o_addqblock(o, str, len);
2102}
2103
Denys Vlasenko38292b62010-09-05 14:49:40 +02002104static void o_addQstr(o_string *o, const char *str)
2105{
2106 o_addQblock(o, str, strlen(str));
2107}
2108
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002109/* A special kind of o_string for $VAR and `cmd` expansion.
2110 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002111 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002112 * list[i] contains an INDEX (int!) into this string data.
2113 * It means that if list[] needs to grow, data needs to be moved higher up
2114 * but list[i]'s need not be modified.
2115 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002116 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002117 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2118 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002119#if DEBUG_EXPAND || DEBUG_GLOB
2120static void debug_print_list(const char *prefix, o_string *o, int n)
2121{
2122 char **list = (char**)o->data;
2123 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2124 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002125
2126 indent();
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002127 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 +02002128 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 +00002129 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002130 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002131 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2132 o->data + (int)list[i] + string_start,
2133 o->data + (int)list[i] + string_start);
2134 i++;
2135 }
2136 if (n) {
2137 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002138 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002139 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002140 }
2141}
2142#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002143# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002144#endif
2145
2146/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2147 * in list[n] so that it points past last stored byte so far.
2148 * It returns n+1. */
2149static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002150{
2151 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002152 int string_start;
2153 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002154
2155 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002156 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2157 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002158 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002159 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002160 /* list[n] points to string_start, make space for 16 more pointers */
2161 o->maxlen += 0x10 * sizeof(list[0]);
2162 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002163 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002164 memmove(list + n + 0x10, list + n, string_len);
2165 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002166 } else {
2167 debug_printf_list("list[%d]=%d string_start=%d\n",
2168 n, string_len, string_start);
2169 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002170 } else {
2171 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002172 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2173 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002174 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2175 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002176 o->has_empty_slot = 0;
2177 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002178 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002179 return n + 1;
2180}
2181
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002182/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002183static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002184{
2185 char **list = (char**)o->data;
2186 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2187
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002188 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002189}
2190
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002191#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002192/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2193 * first, it processes even {a} (no commas), second,
2194 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002195 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002196 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002197
2198/* Helper */
2199static int glob_needed(const char *s)
2200{
2201 while (*s) {
2202 if (*s == '\\') {
2203 if (!s[1])
2204 return 0;
2205 s += 2;
2206 continue;
2207 }
2208 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2209 return 1;
2210 s++;
2211 }
2212 return 0;
2213}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002214/* Return pointer to next closing brace or to comma */
2215static const char *next_brace_sub(const char *cp)
2216{
2217 unsigned depth = 0;
2218 cp++;
2219 while (*cp != '\0') {
2220 if (*cp == '\\') {
2221 if (*++cp == '\0')
2222 break;
2223 cp++;
2224 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002225 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002226 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002227 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002228 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002229 depth++;
2230 }
2231
2232 return *cp != '\0' ? cp : NULL;
2233}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002234/* Recursive brace globber. Note: may garble pattern[]. */
2235static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002236{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002237 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002238 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002239 const char *next;
2240 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002241 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002242 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002243
2244 debug_printf_glob("glob_brace('%s')\n", pattern);
2245
2246 begin = pattern;
2247 while (1) {
2248 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002249 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002250 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002251 /* Find the first sub-pattern and at the same time
2252 * find the rest after the closing brace */
2253 next = next_brace_sub(begin);
2254 if (next == NULL) {
2255 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002256 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002257 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002258 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002259 /* "{abc}" with no commas - illegal
2260 * brace expr, disregard and skip it */
2261 begin = next + 1;
2262 continue;
2263 }
2264 break;
2265 }
2266 if (*begin == '\\' && begin[1] != '\0')
2267 begin++;
2268 begin++;
2269 }
2270 debug_printf_glob("begin:%s\n", begin);
2271 debug_printf_glob("next:%s\n", next);
2272
2273 /* Now find the end of the whole brace expression */
2274 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002275 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002276 rest = next_brace_sub(rest);
2277 if (rest == NULL) {
2278 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002279 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002280 }
2281 debug_printf_glob("rest:%s\n", rest);
2282 }
2283 rest_len = strlen(++rest) + 1;
2284
2285 /* We are sure the brace expression is well-formed */
2286
2287 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002288 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002289
2290 /* We have a brace expression. BEGIN points to the opening {,
2291 * NEXT points past the terminator of the first element, and REST
2292 * points past the final }. We will accumulate result names from
2293 * recursive runs for each brace alternative in the buffer using
2294 * GLOB_APPEND. */
2295
2296 p = begin + 1;
2297 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002298 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002299 memcpy(
2300 mempcpy(
2301 mempcpy(new_pattern_buf,
2302 /* We know the prefix for all sub-patterns */
2303 pattern, begin - pattern),
2304 p, next - p),
2305 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002306
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002307 /* Note: glob_brace() may garble new_pattern_buf[].
2308 * That's why we re-copy prefix every time (1st memcpy above).
2309 */
2310 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002311 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002312 /* We saw the last entry */
2313 break;
2314 }
2315 p = next + 1;
2316 next = next_brace_sub(next);
2317 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002318 free(new_pattern_buf);
2319 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002320
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002321 simple_glob:
2322 {
2323 int gr;
2324 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002325
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002326 memset(&globdata, 0, sizeof(globdata));
2327 gr = glob(pattern, 0, NULL, &globdata);
2328 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2329 if (gr != 0) {
2330 if (gr == GLOB_NOMATCH) {
2331 globfree(&globdata);
2332 /* NB: garbles parameter */
2333 unbackslash(pattern);
2334 o_addstr_with_NUL(o, pattern);
2335 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2336 return o_save_ptr_helper(o, n);
2337 }
2338 if (gr == GLOB_NOSPACE)
2339 bb_error_msg_and_die(bb_msg_memory_exhausted);
2340 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2341 * but we didn't specify it. Paranoia again. */
2342 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2343 }
2344 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2345 char **argv = globdata.gl_pathv;
2346 while (1) {
2347 o_addstr_with_NUL(o, *argv);
2348 n = o_save_ptr_helper(o, n);
2349 argv++;
2350 if (!*argv)
2351 break;
2352 }
2353 }
2354 globfree(&globdata);
2355 }
2356 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002357}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002358/* Performs globbing on last list[],
2359 * saving each result as a new list[].
2360 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002361static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002362{
2363 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002364
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002365 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002366 if (!o->data)
2367 return o_save_ptr_helper(o, n);
2368 pattern = o->data + o_get_last_ptr(o, n);
2369 debug_printf_glob("glob pattern '%s'\n", pattern);
2370 if (!glob_needed(pattern)) {
2371 /* unbackslash last string in o in place, fix length */
2372 o->length = unbackslash(pattern) - o->data;
2373 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2374 return o_save_ptr_helper(o, n);
2375 }
2376
2377 copy = xstrdup(pattern);
2378 /* "forget" pattern in o */
2379 o->length = pattern - o->data;
2380 n = glob_brace(copy, o, n);
2381 free(copy);
2382 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002383 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002384 return n;
2385}
2386
Denys Vlasenko8391c482010-05-22 17:50:43 +02002387#else /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002388
2389/* Helper */
2390static int glob_needed(const char *s)
2391{
2392 while (*s) {
2393 if (*s == '\\') {
2394 if (!s[1])
2395 return 0;
2396 s += 2;
2397 continue;
2398 }
2399 if (*s == '*' || *s == '[' || *s == '?')
2400 return 1;
2401 s++;
2402 }
2403 return 0;
2404}
2405/* Performs globbing on last list[],
2406 * saving each result as a new list[].
2407 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002408static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002409{
2410 glob_t globdata;
2411 int gr;
2412 char *pattern;
2413
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002414 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002415 if (!o->data)
2416 return o_save_ptr_helper(o, n);
2417 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002418 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002419 if (!glob_needed(pattern)) {
2420 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002421 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002422 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002423 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002424 return o_save_ptr_helper(o, n);
2425 }
2426
2427 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002428 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2429 * If we glob "*.\*" and don't find anything, we need
2430 * to fall back to using literal "*.*", but GLOB_NOCHECK
2431 * will return "*.\*"!
2432 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002433 gr = glob(pattern, 0, NULL, &globdata);
2434 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002435 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002436 if (gr == GLOB_NOMATCH) {
2437 globfree(&globdata);
2438 goto literal;
2439 }
2440 if (gr == GLOB_NOSPACE)
2441 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002442 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2443 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002444 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002445 }
2446 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2447 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002448 /* "forget" pattern in o */
2449 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002450 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002451 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002452 n = o_save_ptr_helper(o, n);
2453 argv++;
2454 if (!*argv)
2455 break;
2456 }
2457 }
2458 globfree(&globdata);
2459 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002460 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002461 return n;
2462}
2463
Denys Vlasenko8391c482010-05-22 17:50:43 +02002464#endif /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002465
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002466/* If o->o_glob == 1, glob the string so far remembered.
2467 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002468static int o_save_ptr(o_string *o, int n)
2469{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002470 if (o->o_glob) { /* if globbing is requested */
2471 /* If o->has_empty_slot, list[n] was already globbed
2472 * (if it was requested back then when it was filled)
2473 * so don't do that again! */
2474 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002475 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002476 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002477 return o_save_ptr_helper(o, n);
2478}
2479
2480/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002481static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002482{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002483 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002484 int string_start;
2485
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002486 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2487 if (DEBUG_EXPAND)
2488 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002489 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002490 list = (char**)o->data;
2491 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2492 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002493 while (n) {
2494 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002495 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002496 }
2497 return list;
2498}
2499
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002500static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002501
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002502/* Returns pi->next - next pipe in the list */
2503static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002504{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002505 struct pipe *next;
2506 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002507
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002508 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002509 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002510 struct command *command;
2511 struct redir_struct *r, *rnext;
2512
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002513 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002514 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002515 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002516 if (DEBUG_CLEAN) {
2517 int a;
2518 char **p;
2519 for (a = 0, p = command->argv; *p; a++, p++) {
2520 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2521 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002522 }
2523 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002524 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002525 }
2526 /* not "else if": on syntax error, we may have both! */
2527 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002528 debug_printf_clean(" begin group (cmd_type:%d)\n",
2529 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002530 free_pipe_list(command->group);
2531 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002532 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002533 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002534 /* else is crucial here.
2535 * If group != NULL, child_func is meaningless */
2536#if ENABLE_HUSH_FUNCTIONS
2537 else if (command->child_func) {
2538 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2539 command->child_func->parent_cmd = NULL;
2540 }
2541#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002542#if !BB_MMU
2543 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002544 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002545#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002546 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002547 debug_printf_clean(" redirect %d%s",
2548 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002549 /* guard against the case >$FOO, where foo is unset or blank */
2550 if (r->rd_filename) {
2551 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2552 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002553 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002554 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002555 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556 rnext = r->next;
2557 free(r);
2558 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002559 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002560 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002561 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002562 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002563#if ENABLE_HUSH_JOB
2564 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002565 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002566#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002567
2568 next = pi->next;
2569 free(pi);
2570 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002571}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002572
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002573static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002574{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002575 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002576#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002577 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002578#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002579 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002580 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002581 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002582}
2583
2584
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002585/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002586
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002587static struct pipe *new_pipe(void)
2588{
Eric Andersen25f27032001-04-26 23:22:31 +00002589 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002590 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002591 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002592 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002593 return pi;
2594}
2595
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002596/* Command (member of a pipe) is complete, or we start a new pipe
2597 * if ctx->command is NULL.
2598 * No errors possible here.
2599 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002600static int done_command(struct parse_context *ctx)
2601{
2602 /* The command is really already in the pipe structure, so
2603 * advance the pipe counter and make a new, null command. */
2604 struct pipe *pi = ctx->pipe;
2605 struct command *command = ctx->command;
2606
2607 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002608 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002609 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002610 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002611 }
2612 pi->num_cmds++;
2613 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002614 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002615 } else {
2616 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2617 }
2618
2619 /* Only real trickiness here is that the uncommitted
2620 * command structure is not counted in pi->num_cmds. */
2621 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002622 ctx->command = command = &pi->cmds[pi->num_cmds];
2623 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002624 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002625 return pi->num_cmds; /* used only for 0/nonzero check */
2626}
2627
2628static void done_pipe(struct parse_context *ctx, pipe_style type)
2629{
2630 int not_null;
2631
2632 debug_printf_parse("done_pipe entered, followup %d\n", type);
2633 /* Close previous command */
2634 not_null = done_command(ctx);
2635 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002636#if HAS_KEYWORDS
2637 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2638 ctx->ctx_inverted = 0;
2639 ctx->pipe->res_word = ctx->ctx_res_w;
2640#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002641
2642 /* Without this check, even just <enter> on command line generates
2643 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002644 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002645 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002646#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002647 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002648#endif
2649#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002650 || ctx->ctx_res_w == RES_DONE
2651 || ctx->ctx_res_w == RES_FOR
2652 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002653#endif
2654#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002655 || ctx->ctx_res_w == RES_ESAC
2656#endif
2657 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002658 struct pipe *new_p;
2659 debug_printf_parse("done_pipe: adding new pipe: "
2660 "not_null:%d ctx->ctx_res_w:%d\n",
2661 not_null, ctx->ctx_res_w);
2662 new_p = new_pipe();
2663 ctx->pipe->next = new_p;
2664 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002665 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002666 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002667 * This is used to control execution.
2668 * RES_FOR and RES_IN are NOT sticky (needed to support
2669 * cases where variable or value happens to match a keyword):
2670 */
2671#if ENABLE_HUSH_LOOPS
2672 if (ctx->ctx_res_w == RES_FOR
2673 || ctx->ctx_res_w == RES_IN)
2674 ctx->ctx_res_w = RES_NONE;
2675#endif
2676#if ENABLE_HUSH_CASE
2677 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002678 ctx->ctx_res_w = RES_CASE_BODY;
2679 if (ctx->ctx_res_w == RES_CASE)
2680 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002681#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002682 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002683 /* Create the memory for command, roughly:
2684 * ctx->pipe->cmds = new struct command;
2685 * ctx->command = &ctx->pipe->cmds[0];
2686 */
2687 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002688 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002689 }
2690 debug_printf_parse("done_pipe return\n");
2691}
2692
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002693static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002694{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002695 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002696 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002697 /* Create the memory for command, roughly:
2698 * ctx->pipe->cmds = new struct command;
2699 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002700 */
2701 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002702}
2703
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002704/* If a reserved word is found and processed, parse context is modified
2705 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002706 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002707#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002708struct reserved_combo {
2709 char literal[6];
2710 unsigned char res;
2711 unsigned char assignment_flag;
2712 int flag;
2713};
2714enum {
2715 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002716# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002717 FLAG_IF = (1 << RES_IF ),
2718 FLAG_THEN = (1 << RES_THEN ),
2719 FLAG_ELIF = (1 << RES_ELIF ),
2720 FLAG_ELSE = (1 << RES_ELSE ),
2721 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002722# endif
2723# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002724 FLAG_FOR = (1 << RES_FOR ),
2725 FLAG_WHILE = (1 << RES_WHILE),
2726 FLAG_UNTIL = (1 << RES_UNTIL),
2727 FLAG_DO = (1 << RES_DO ),
2728 FLAG_DONE = (1 << RES_DONE ),
2729 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002730# endif
2731# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002732 FLAG_MATCH = (1 << RES_MATCH),
2733 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002734# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002735 FLAG_START = (1 << RES_XXXX ),
2736};
2737
2738static const struct reserved_combo* match_reserved_word(o_string *word)
2739{
Eric Andersen25f27032001-04-26 23:22:31 +00002740 /* Mostly a list of accepted follow-up reserved words.
2741 * FLAG_END means we are done with the sequence, and are ready
2742 * to turn the compound list into a command.
2743 * FLAG_START means the word must start a new compound list.
2744 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002745 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002746# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002747 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2748 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2749 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2750 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2751 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2752 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002753# endif
2754# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002755 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2756 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2757 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2758 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2759 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2760 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002761# endif
2762# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002763 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2764 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002765# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002766 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002767 const struct reserved_combo *r;
2768
2769 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2770 if (strcmp(word->data, r->literal) == 0)
2771 return r;
2772 }
2773 return NULL;
2774}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002775/* Return 0: not a keyword, 1: keyword
2776 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002777static int reserved_word(o_string *word, struct parse_context *ctx)
2778{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002779# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002780 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002781 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002782 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002783# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002784 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002785
Denys Vlasenko38292b62010-09-05 14:49:40 +02002786 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002787 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002788 r = match_reserved_word(word);
2789 if (!r)
2790 return 0;
2791
2792 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002793# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002794 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2795 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002796 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002797 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002798# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002799 if (r->flag == 0) { /* '!' */
2800 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002801 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002802 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002803 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002804 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002805 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002806 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002807 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002808 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002809
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002810 old = xmalloc(sizeof(*old));
2811 debug_printf_parse("push stack %p\n", old);
2812 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002813 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002814 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002815 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002816 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002817 ctx->ctx_res_w = RES_SNTX;
2818 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002819 } else {
2820 /* "{...} fi" is ok. "{...} if" is not
2821 * Example:
2822 * if { echo foo; } then { echo bar; } fi */
2823 if (ctx->command->group)
2824 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002825 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002826
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002827 ctx->ctx_res_w = r->res;
2828 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002829 word->o_assignment = r->assignment_flag;
2830
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002831 if (ctx->old_flag & FLAG_END) {
2832 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002833
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002834 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002835 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002836 old = ctx->stack;
2837 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002838 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002839# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002840 o_addstr(&old->as_string, ctx->as_string.data);
2841 o_free_unsafe(&ctx->as_string);
2842 old->command->group_as_string = xstrdup(old->as_string.data);
2843 debug_printf_parse("pop, remembering as:'%s'\n",
2844 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002845# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002846 *ctx = *old; /* physical copy */
2847 free(old);
2848 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002849 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002850}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002851#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00002852
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002853/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002854 * Normal return is 0. Syntax errors return 1.
2855 * Note: on return, word is reset, but not o_free'd!
2856 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002857static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002858{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002859 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00002860
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002861 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02002862 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002863 debug_printf_parse("done_word return 0: true null, ignored\n");
2864 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002865 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002866
Eric Andersen25f27032001-04-26 23:22:31 +00002867 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002868 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2869 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002870 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2871 * "2.7 Redirection
2872 * ...the word that follows the redirection operator
2873 * shall be subjected to tilde expansion, parameter expansion,
2874 * command substitution, arithmetic expansion, and quote
2875 * removal. Pathname expansion shall not be performed
2876 * on the word by a non-interactive shell; an interactive
2877 * shell may perform it, but shall do so only when
2878 * the expansion would result in one word."
2879 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002880 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002881 /* Cater for >\file case:
2882 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2883 * Same with heredocs:
2884 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2885 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002886 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2887 unbackslash(ctx->pending_redirect->rd_filename);
2888 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02002889 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002890 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2891 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002892 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002893 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002894 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002895 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002896 /* If this word wasn't an assignment, next ones definitely
2897 * can't be assignments. Even if they look like ones. */
2898 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2899 && word->o_assignment != WORD_IS_KEYWORD
2900 ) {
2901 word->o_assignment = NOT_ASSIGNMENT;
2902 } else {
2903 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2904 command->assignment_cnt++;
2905 word->o_assignment = MAYBE_ASSIGNMENT;
2906 }
2907
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002908#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002909# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00002910 if (ctx->ctx_dsemicolon
2911 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2912 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00002913 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002914 /* ctx->ctx_res_w = RES_MATCH; */
2915 ctx->ctx_dsemicolon = 0;
2916 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002917# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002918 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002919# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002920 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2921 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002922# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002923# if ENABLE_HUSH_CASE
2924 && ctx->ctx_res_w != RES_CASE
2925# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002926 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002927 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002928 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002929 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002930 debug_printf_parse("done_word return %d\n",
2931 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002932 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002933 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002934# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002935 if (strcmp(word->data, "[[") == 0) {
2936 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2937 }
2938 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002939# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002940 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002941#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00002942 if (command->group) {
2943 /* "{ echo foo; } echo bar" - bad */
2944 syntax_error_at(word->data);
2945 debug_printf_parse("done_word return 1: syntax error, "
2946 "groups and arglists don't mix\n");
2947 return 1;
2948 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02002949 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00002950 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2951 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002952 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002953 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002954 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002955 char *p = word->data;
2956 while (p[0] == SPECIAL_VAR_SYMBOL
2957 && (p[1] & 0x7f) == '@'
2958 && p[2] == SPECIAL_VAR_SYMBOL
2959 ) {
2960 p += 3;
2961 }
2962 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002963 /* saw no "$@", or not only "$@" but some
2964 * real text is there too */
2965 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002966 * e.g. "", $empty"" etc to not disappear */
2967 o_addchr(word, SPECIAL_VAR_SYMBOL);
2968 o_addchr(word, SPECIAL_VAR_SYMBOL);
2969 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002970 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002971 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002972 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002973 }
Eric Andersen25f27032001-04-26 23:22:31 +00002974
Denis Vlasenko06810332007-05-21 23:30:54 +00002975#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002976 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02002977 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002978 || !is_well_formed_var_name(command->argv[0], '\0')
2979 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002980 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002981 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002982 return 1;
2983 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002984 /* Force FOR to have just one word (variable name) */
2985 /* NB: basically, this makes hush see "for v in ..."
2986 * syntax as if it is "for v; in ...". FOR and IN become
2987 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002988 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002989 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002990#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002991#if ENABLE_HUSH_CASE
2992 /* Force CASE to have just one word */
2993 if (ctx->ctx_res_w == RES_CASE) {
2994 done_pipe(ctx, PIPE_SEQ);
2995 }
2996#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002997
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002998 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002999
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003000 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003001 return 0;
3002}
3003
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003004
3005/* Peek ahead in the input to find out if we have a "&n" construct,
3006 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003007 * Return:
3008 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3009 * REDIRFD_SYNTAX_ERR if syntax error,
3010 * REDIRFD_TO_FILE if no & was seen,
3011 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003012 */
3013#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003014#define parse_redir_right_fd(as_string, input) \
3015 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003016#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003017static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003018{
3019 int ch, d, ok;
3020
3021 ch = i_peek(input);
3022 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003023 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003024
3025 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003026 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003027 ch = i_peek(input);
3028 if (ch == '-') {
3029 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003030 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003031 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003032 }
3033 d = 0;
3034 ok = 0;
3035 while (ch != EOF && isdigit(ch)) {
3036 d = d*10 + (ch-'0');
3037 ok = 1;
3038 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003039 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003040 ch = i_peek(input);
3041 }
3042 if (ok) return d;
3043
3044//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3045
3046 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003047 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003048}
3049
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003050/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003051 */
3052static int parse_redirect(struct parse_context *ctx,
3053 int fd,
3054 redir_type style,
3055 struct in_str *input)
3056{
3057 struct command *command = ctx->command;
3058 struct redir_struct *redir;
3059 struct redir_struct **redirp;
3060 int dup_num;
3061
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003062 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003063 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003064 /* Check for a '>&1' type redirect */
3065 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3066 if (dup_num == REDIRFD_SYNTAX_ERR)
3067 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003068 } else {
3069 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003070 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003071 if (dup_num) { /* <<-... */
3072 ch = i_getch(input);
3073 nommu_addchr(&ctx->as_string, ch);
3074 ch = i_peek(input);
3075 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003076 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003077
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003078 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003079 int ch = i_peek(input);
3080 if (ch == '|') {
3081 /* >|FILE redirect ("clobbering" >).
3082 * Since we do not support "set -o noclobber" yet,
3083 * >| and > are the same for now. Just eat |.
3084 */
3085 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003086 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003087 }
3088 }
3089
3090 /* Create a new redir_struct and append it to the linked list */
3091 redirp = &command->redirects;
3092 while ((redir = *redirp) != NULL) {
3093 redirp = &(redir->next);
3094 }
3095 *redirp = redir = xzalloc(sizeof(*redir));
3096 /* redir->next = NULL; */
3097 /* redir->rd_filename = NULL; */
3098 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003099 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003100
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003101 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3102 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003103
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003104 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003105 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003106 /* Erik had a check here that the file descriptor in question
3107 * is legit; I postpone that to "run time"
3108 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003109 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3110 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003111 } else {
3112 /* Set ctx->pending_redirect, so we know what to do at the
3113 * end of the next parsed word. */
3114 ctx->pending_redirect = redir;
3115 }
3116 return 0;
3117}
3118
Eric Andersen25f27032001-04-26 23:22:31 +00003119/* If a redirect is immediately preceded by a number, that number is
3120 * supposed to tell which file descriptor to redirect. This routine
3121 * looks for such preceding numbers. In an ideal world this routine
3122 * needs to handle all the following classes of redirects...
3123 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3124 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3125 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3126 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003127 *
3128 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3129 * "2.7 Redirection
3130 * ... If n is quoted, the number shall not be recognized as part of
3131 * the redirection expression. For example:
3132 * echo \2>a
3133 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003134 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003135 *
3136 * A -1 return means no valid number was found,
3137 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003138 */
3139static int redirect_opt_num(o_string *o)
3140{
3141 int num;
3142
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003143 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003144 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003145 num = bb_strtou(o->data, NULL, 10);
3146 if (errno || num < 0)
3147 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003148 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003149 return num;
3150}
3151
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003152#if BB_MMU
3153#define fetch_till_str(as_string, input, word, skip_tabs) \
3154 fetch_till_str(input, word, skip_tabs)
3155#endif
3156static char *fetch_till_str(o_string *as_string,
3157 struct in_str *input,
3158 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003159 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003160{
3161 o_string heredoc = NULL_O_STRING;
3162 int past_EOL = 0;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003163 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003164 int ch;
3165
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003166 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003167 while (1) {
3168 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003169 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003170 if (ch == '\n'
Denys Vlasenko83b900f2010-09-06 11:47:55 +02003171 /* TODO: or EOF? (heredoc delimiter may end with <eof>, not only <eol>) */
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003172 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3173 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003174 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3175 heredoc.data[past_EOL] = '\0';
3176 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3177 return heredoc.data;
3178 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003179 do {
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003180 o_addchr(&heredoc, '\n');
3181 prev = 0; /* not \ */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003182 past_EOL = heredoc.length;
3183 jump_in:
3184 do {
3185 ch = i_getch(input);
3186 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003187 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003188 } while (ch == '\n');
3189 }
3190 if (ch == EOF) {
3191 o_free_unsafe(&heredoc);
3192 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003193 }
3194 o_addchr(&heredoc, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003195 if (prev == '\\' && ch == '\\')
3196 /* Correctly handle foo\\<eol> (not a line cont.) */
3197 prev = 0; /* not \ */
3198 else
3199 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003200 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003201 }
3202}
3203
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003204/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3205 * and load them all. There should be exactly heredoc_cnt of them.
3206 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003207static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3208{
3209 struct pipe *pi = ctx->list_head;
3210
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003211 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003212 int i;
3213 struct command *cmd = pi->cmds;
3214
3215 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3216 pi->num_cmds,
3217 cmd->argv ? cmd->argv[0] : "NONE");
3218 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003219 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003220
3221 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3222 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003223 while (redir) {
3224 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003225 char *p;
3226
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003227 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003228 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003229 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003230 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003231 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003232 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003233 return 1;
3234 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003235 free(redir->rd_filename);
3236 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003237 heredoc_cnt--;
3238 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003239 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003240 }
3241 cmd++;
3242 }
3243 pi = pi->next;
3244 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003245#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003246 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003247 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003248 bb_error_msg_and_die("heredoc BUG 2");
3249#endif
3250 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003251}
3252
3253
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003254static int run_list(struct pipe *pi);
3255#if BB_MMU
3256#define parse_stream(pstring, input, end_trigger) \
3257 parse_stream(input, end_trigger)
3258#endif
3259static struct pipe *parse_stream(char **pstring,
3260 struct in_str *input,
3261 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003262
Eric Andersen25f27032001-04-26 23:22:31 +00003263
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003264#if !ENABLE_HUSH_FUNCTIONS
3265#define parse_group(dest, ctx, input, ch) \
3266 parse_group(ctx, input, ch)
3267#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003268static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003269 struct in_str *input, int ch)
3270{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003271 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003272 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003273 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003274 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003275 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003276 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003277
3278 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003279#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003280 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003281 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003282 if (done_word(dest, ctx))
3283 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003284 if (!command->argv)
3285 goto skip; /* (... */
3286 if (command->argv[1]) { /* word word ... (... */
3287 syntax_error_unexpected_ch('(');
3288 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003289 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003290 /* it is "word(..." or "word (..." */
3291 do
3292 ch = i_getch(input);
3293 while (ch == ' ' || ch == '\t');
3294 if (ch != ')') {
3295 syntax_error_unexpected_ch(ch);
3296 return 1;
3297 }
3298 nommu_addchr(&ctx->as_string, ch);
3299 do
3300 ch = i_getch(input);
3301 while (ch == ' ' || ch == '\t' || ch == '\n');
3302 if (ch != '{') {
3303 syntax_error_unexpected_ch(ch);
3304 return 1;
3305 }
3306 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003307 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003308 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003309 }
3310#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003311
3312#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003313 if (command->argv /* word [word]{... */
3314 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003315 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003316 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003317 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003318 debug_printf_parse("parse_group return 1: "
3319 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003320 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003321 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003322#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003323
3324#if ENABLE_HUSH_FUNCTIONS
3325 skip:
3326#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003327 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003328 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003329 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003330 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003331 } else {
3332 /* bash does not allow "{echo...", requires whitespace */
3333 ch = i_getch(input);
3334 if (ch != ' ' && ch != '\t' && ch != '\n') {
3335 syntax_error_unexpected_ch(ch);
3336 return 1;
3337 }
3338 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003339 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003340
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003341 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003342#if BB_MMU
3343# define as_string NULL
3344#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003345 char *as_string = NULL;
3346#endif
3347 pipe_list = parse_stream(&as_string, input, endch);
3348#if !BB_MMU
3349 if (as_string)
3350 o_addstr(&ctx->as_string, as_string);
3351#endif
3352 /* empty ()/{} or parse error? */
3353 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003354 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003355 if (!BB_MMU)
3356 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003357 debug_printf_parse("parse_group return 1: "
3358 "parse_stream returned %p\n", pipe_list);
3359 return 1;
3360 }
3361 command->group = pipe_list;
3362#if !BB_MMU
3363 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3364 command->group_as_string = as_string;
3365 debug_printf_parse("end of group, remembering as:'%s'\n",
3366 command->group_as_string);
3367#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003368#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003369 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003370 debug_printf_parse("parse_group return 0\n");
3371 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003372 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003373}
3374
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003375#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003376/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003377static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003378/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003379static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003380{
3381 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003382 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003383 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003384 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003385 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003386 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003387 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003388 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003389 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003390 }
3391}
3392/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003393static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003394{
3395 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003396 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003397 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003398 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003399 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003400 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003401 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003402 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003403 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003404 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003405 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003406 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003407 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003408 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003409 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003410 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003411 continue;
3412 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003413 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003414 }
3415}
3416/* Process `cmd` - copy contents until "`" is seen. Complicated by
3417 * \` quoting.
3418 * "Within the backquoted style of command substitution, backslash
3419 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3420 * The search for the matching backquote shall be satisfied by the first
3421 * backquote found without a preceding backslash; during this search,
3422 * if a non-escaped backquote is encountered within a shell comment,
3423 * a here-document, an embedded command substitution of the $(command)
3424 * form, or a quoted string, undefined results occur. A single-quoted
3425 * or double-quoted string that begins, but does not end, within the
3426 * "`...`" sequence produces undefined results."
3427 * Example Output
3428 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3429 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003430static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003431{
3432 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003433 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003434 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003435 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003436 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003437 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003438 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003439 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003440 if (ch == '\\') {
3441 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003442 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003443 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003444 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003445 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003446 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003447 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003448 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003449 ch = ch2;
3450 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003451 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003452 }
3453}
3454/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3455 * quoting and nested ()s.
3456 * "With the $(command) style of command substitution, all characters
3457 * following the open parenthesis to the matching closing parenthesis
3458 * constitute the command. Any valid shell script can be used for command,
3459 * except a script consisting solely of redirections which produces
3460 * unspecified results."
3461 * Example Output
3462 * echo $(echo '(TEST)' BEST) (TEST) BEST
3463 * echo $(echo 'TEST)' BEST) TEST) BEST
3464 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003465 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003466 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003467 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003468 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3469 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003470 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003471#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003472static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003473{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003474 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003475 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003476# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003477 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003478# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003479 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3480
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003481 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003482 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003483 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003484 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003485 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003486 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003487 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003488 if (!dbl)
3489 break;
3490 /* we look for closing )) of $((EXPR)) */
3491 if (i_peek(input) == end_ch) {
3492 i_getch(input); /* eat second ')' */
3493 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003494 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003495 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003496 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003497 if (ch == '(' || ch == '{') {
3498 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003499 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003500 o_addchr(dest, ch);
3501 continue;
3502 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003503 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003504 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003505 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003506 continue;
3507 }
3508 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003509 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003510 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003511 continue;
3512 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003513 if (ch == '`') {
3514 add_till_backquote(dest, input);
3515 o_addchr(dest, ch);
3516 continue;
3517 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003518 if (ch == '\\') {
3519 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003520 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003521 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003522 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003523 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003524 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003525 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003526 continue;
3527 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003528 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003529 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003530}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003531#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003532
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003533/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003534#if BB_MMU
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003535#define parse_dollar(as_string, dest, input) \
3536 parse_dollar(dest, input)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003537#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003538#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003539static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003540 o_string *dest,
3541 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003542{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003543 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003544 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003545
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003546 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003547 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003548 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003549 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003550 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003551 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003552 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003553 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003554 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003555 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003556 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003557 if (!isalnum(ch) && ch != '_')
3558 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003559 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003560 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003561 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003562 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003563 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003564 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003565 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003566 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003567 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003568 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003569 o_addchr(dest, ch | quote_mask);
3570 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003571 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003572 case '$': /* pid */
3573 case '!': /* last bg pid */
3574 case '?': /* last exit code */
3575 case '#': /* number of args */
3576 case '*': /* args */
3577 case '@': /* args */
3578 goto make_one_char_var;
3579 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003580 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3581
Denys Vlasenko74369502010-05-21 19:52:01 +02003582 ch = i_getch(input); /* eat '{' */
3583 nommu_addchr(as_string, ch);
3584
3585 ch = i_getch(input); /* first char after '{' */
3586 nommu_addchr(as_string, ch);
3587 /* It should be ${?}, or ${#var},
3588 * or even ${?+subst} - operator acting on a special variable,
3589 * or the beginning of variable name.
3590 */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02003591 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
Denys Vlasenko74369502010-05-21 19:52:01 +02003592 bad_dollar_syntax:
3593 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003594 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003595 return 1;
3596 }
3597 ch |= quote_mask;
3598
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003599 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003600 * However, this regresses some of our testsuite cases
3601 * which check invalid constructs like ${%}.
3602 * Oh well... let's check that the var name part is fine... */
3603
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003604 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003605 unsigned pos;
3606
Denys Vlasenko74369502010-05-21 19:52:01 +02003607 o_addchr(dest, ch);
3608 debug_printf_parse(": '%c'\n", ch);
3609
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003610 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003611 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003612 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003613 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003614
Denys Vlasenko74369502010-05-21 19:52:01 +02003615 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003616 unsigned end_ch;
3617 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003618 /* handle parameter expansions
3619 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3620 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003621 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003622 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003623
3624 /* Eat everything until closing '}' (or ':') */
3625 end_ch = '}';
3626 if (ENABLE_HUSH_BASH_COMPAT
3627 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003628 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003629 ) {
3630 /* It's ${var:N[:M]} thing */
3631 end_ch = '}' * 0x100 + ':';
3632 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003633 if (ENABLE_HUSH_BASH_COMPAT
3634 && ch == '/'
3635 ) {
3636 /* It's ${var/[/]pattern[/repl]} thing */
3637 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3638 i_getch(input);
3639 nommu_addchr(as_string, '/');
3640 ch = '\\';
3641 }
3642 end_ch = '}' * 0x100 + '/';
3643 }
3644 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003645 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003646 if (!BB_MMU)
3647 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003648#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003649 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003650#else
3651#error Simple code to only allow ${var} is not implemented
3652#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003653 if (as_string) {
3654 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003655 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003656 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003657
3658 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3659 /* close the first block: */
3660 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003661 /* while parsing N from ${var:N[:M]}
3662 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003663 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003664 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003665 end_ch = '}';
3666 goto again;
3667 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003668 /* got '}' */
3669 if (end_ch == '}' * 0x100 + ':') {
3670 /* it's ${var:N} - emulate :999999999 */
3671 o_addstr(dest, "999999999");
3672 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003673 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003674 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003675 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003676 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003677 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3678 break;
3679 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003680#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003681 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003682 unsigned pos;
3683
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003684 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003685 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003686# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003687 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003688 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003689 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003690 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3691 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003692 if (!BB_MMU)
3693 pos = dest->length;
3694 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003695 if (as_string) {
3696 o_addstr(as_string, dest->data + pos);
3697 o_addchr(as_string, ')');
3698 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003699 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003701 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003702 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003703# endif
3704# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3706 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003707 if (!BB_MMU)
3708 pos = dest->length;
3709 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003710 if (as_string) {
3711 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003712 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003713 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003714 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003715# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003716 break;
3717 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003718#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003719 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003720 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003721 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003722 ch = i_peek(input);
3723 if (isalnum(ch)) { /* it's $_name or $_123 */
3724 ch = '_';
3725 goto make_var;
3726 }
3727 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003728 /* TODO: $_ and $-: */
3729 /* $_ Shell or shell script name; or last argument of last command
3730 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3731 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003732 /* $- Option flags set by set builtin or shell options (-i etc) */
3733 default:
3734 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003735 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003736 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003737 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003738#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003739}
3740
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003741#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003742#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003743 parse_stream_dquoted(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003744#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003745#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003746static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003747 o_string *dest,
3748 struct in_str *input,
3749 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003750{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003751 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003752 int next;
3753
3754 again:
3755 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003756 if (ch != EOF)
3757 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003758 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003759 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003760 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003761 debug_printf_parse("parse_stream_dquoted return 0\n");
3762 return 0;
3763 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003764 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003765 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003766 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003767 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003768 }
3769 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003770 if (ch != '\n') {
3771 next = i_peek(input);
3772 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003773 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003774 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003775 if (ch == '\\') {
3776 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003777 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003778 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003779 }
3780 /* bash:
3781 * "The backslash retains its special meaning [in "..."]
3782 * only when followed by one of the following characters:
3783 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003784 * within double quotes by preceding it with a backslash."
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003785 * NB: in (unquoted) heredoc, above does not apply to ".
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003786 */
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003787 if (next == dquote_end || strchr("$`\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00003788 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02003789 if (ch != '\n') {
3790 o_addqchr(dest, ch);
3791 nommu_addchr(as_string, ch);
3792 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003793 } else {
3794 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00003795 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003796 }
3797 goto again;
3798 }
3799 if (ch == '$') {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003800 if (parse_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003801 debug_printf_parse("parse_stream_dquoted return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003802 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003803 return 1;
3804 }
3805 goto again;
3806 }
3807#if ENABLE_HUSH_TICK
3808 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003809 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003810 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3811 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003812 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003813 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3814 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003815 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003816 }
3817#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003818 o_addQchr(dest, ch);
3819 if (ch == '='
3820 && (dest->o_assignment == MAYBE_ASSIGNMENT
3821 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003822 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00003823 ) {
3824 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3825 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003826 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003827#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003828}
3829
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003830/*
3831 * Scan input until EOF or end_trigger char.
3832 * Return a list of pipes to execute, or NULL on EOF
3833 * or if end_trigger character is met.
3834 * On syntax error, exit is shell is not interactive,
3835 * reset parsing machinery and start parsing anew,
3836 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003837 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003838static struct pipe *parse_stream(char **pstring,
3839 struct in_str *input,
3840 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003841{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003842 struct parse_context ctx;
3843 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003844 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003845 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00003846
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003847 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00003848 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003849 * found. When recursing, quote state is passed in via dest->o_escape.
3850 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003851 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02003852 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003853 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003854
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003855 /* If very first arg is "" or '', dest.data may end up NULL.
3856 * Preventing this: */
3857 o_addchr(&dest, '\0');
3858 dest.length = 0;
3859
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003860 G.ifs = get_local_var_value("IFS");
3861 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01003862 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003863
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003864 reset:
3865#if ENABLE_HUSH_INTERACTIVE
3866 input->promptmode = 0; /* PS1 */
3867#endif
3868 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
3869 initialize_context(&ctx);
3870 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003871 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003872 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003873 const char *is_ifs;
3874 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003875 int ch;
3876 int next;
3877 int redir_fd;
3878 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003879
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003880 if (is_in_dquote) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003881 /* dest.has_quoted_part = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003882 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003883 goto parse_error;
3884 }
3885 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003886 is_in_dquote = 0;
3887 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003888 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003889 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3890 ch, ch, dest.o_escape);
3891 if (ch == EOF) {
3892 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003893
3894 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003895 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003896 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003897 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003898 /* end_trigger == '}' case errors out earlier,
3899 * checking only ')' */
3900 if (end_trigger == ')') {
3901 syntax_error_unterm_ch('('); /* exits */
3902 /* goto parse_error; */
3903 }
3904
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003905 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003906 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003907 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003908 o_free(&dest);
3909 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003910 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003911 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003912 /* (this makes bare "&" cmd a no-op.
3913 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003914 if (pi->num_cmds == 0
3915 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3916 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003917 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003918 pi = NULL;
3919 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003920#if !BB_MMU
3921 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3922 if (pstring)
3923 *pstring = ctx.as_string.data;
3924 else
3925 o_free_unsafe(&ctx.as_string);
3926#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003927 debug_leave();
3928 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003929 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003930 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003931 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003932
3933 next = '\0';
3934 if (ch != '\n')
3935 next = i_peek(input);
3936
3937 is_special = "{}<>;&|()#'" /* special outside of "str" */
3938 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3939 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003940 if (ctx.command->argv /* word [word]{... - non-special */
3941 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003942 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003943 || (next != ';' /* }; - special */
3944 && next != ')' /* }) - special */
3945 && next != '&' /* }& and }&& ... - special */
3946 && next != '|' /* }|| ... - special */
3947 && !strchr(G.ifs, next) /* {word - non-special */
3948 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003949 ) {
3950 /* They are not special, skip "{}" */
3951 is_special += 2;
3952 }
3953 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003954 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003955
3956 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003957 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003958 o_addQchr(&dest, ch);
3959 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3960 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003961 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003962 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00003963 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003964 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003965 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003966 continue;
3967 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00003968
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003969 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003970 if (done_word(&dest, &ctx)) {
3971 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00003972 }
Denis Vlasenko37181682009-04-03 03:19:15 +00003973 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003974#if ENABLE_HUSH_CASE
3975 /* "case ... in <newline> word) ..." -
3976 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003977 if (ctx.command->argv == NULL
3978 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00003979 ) {
3980 continue;
3981 }
3982#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003983 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003984 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003985 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3986 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003987 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003988 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003989 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003990 heredoc_cnt = 0;
3991 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003992 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003993 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00003994 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003995 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003996 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003997 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00003998
3999 /* "cmd}" or "cmd }..." without semicolon or &:
4000 * } is an ordinary char in this case, even inside { cmd; }
4001 * Pathological example: { ""}; } should exec "}" cmd
4002 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004003 if (ch == '}') {
4004 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4005 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004006 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004007 ) {
4008 goto ordinary_char;
4009 }
4010 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4011 goto skip_end_trigger;
4012 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004013 }
4014
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004015 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004016 && (ch != ';' || heredoc_cnt == 0)
4017#if ENABLE_HUSH_CASE
4018 && (ch != ')'
4019 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004020 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004021 )
4022#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004023 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004024 if (heredoc_cnt) {
4025 /* This is technically valid:
4026 * { cat <<HERE; }; echo Ok
4027 * heredoc
4028 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004029 * HERE
4030 * but we don't support this.
4031 * We require heredoc to be in enclosing {}/(),
4032 * if any.
4033 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004034 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004035 goto parse_error;
4036 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004037 if (done_word(&dest, &ctx)) {
4038 goto parse_error;
4039 }
4040 done_pipe(&ctx, PIPE_SEQ);
4041 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004042 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004043 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004044 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004045 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004046 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004047#if !BB_MMU
4048 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4049 if (pstring)
4050 *pstring = ctx.as_string.data;
4051 else
4052 o_free_unsafe(&ctx.as_string);
4053#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004054 debug_leave();
4055 debug_printf_parse("parse_stream return %p: "
4056 "end_trigger char found\n",
4057 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004058 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004059 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004060 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004061 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004062 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004063 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004064
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004065 /* Catch <, > before deciding whether this word is
4066 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4067 switch (ch) {
4068 case '>':
4069 redir_fd = redirect_opt_num(&dest);
4070 if (done_word(&dest, &ctx)) {
4071 goto parse_error;
4072 }
4073 redir_style = REDIRECT_OVERWRITE;
4074 if (next == '>') {
4075 redir_style = REDIRECT_APPEND;
4076 ch = i_getch(input);
4077 nommu_addchr(&ctx.as_string, ch);
4078 }
4079#if 0
4080 else if (next == '(') {
4081 syntax_error(">(process) not supported");
4082 goto parse_error;
4083 }
4084#endif
4085 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4086 goto parse_error;
4087 continue; /* back to top of while (1) */
4088 case '<':
4089 redir_fd = redirect_opt_num(&dest);
4090 if (done_word(&dest, &ctx)) {
4091 goto parse_error;
4092 }
4093 redir_style = REDIRECT_INPUT;
4094 if (next == '<') {
4095 redir_style = REDIRECT_HEREDOC;
4096 heredoc_cnt++;
4097 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4098 ch = i_getch(input);
4099 nommu_addchr(&ctx.as_string, ch);
4100 } else if (next == '>') {
4101 redir_style = REDIRECT_IO;
4102 ch = i_getch(input);
4103 nommu_addchr(&ctx.as_string, ch);
4104 }
4105#if 0
4106 else if (next == '(') {
4107 syntax_error("<(process) not supported");
4108 goto parse_error;
4109 }
4110#endif
4111 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4112 goto parse_error;
4113 continue; /* back to top of while (1) */
4114 }
4115
4116 if (dest.o_assignment == MAYBE_ASSIGNMENT
4117 /* check that we are not in word in "a=1 2>word b=1": */
4118 && !ctx.pending_redirect
4119 ) {
4120 /* ch is a special char and thus this word
4121 * cannot be an assignment */
4122 dest.o_assignment = NOT_ASSIGNMENT;
4123 }
4124
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004125 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4126
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004127 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00004128 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004129 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004130 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004131 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004132 if (ch == EOF || ch == '\n')
4133 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004134 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004135 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004136 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004137 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00004138 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004139 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004140 }
4141 break;
4142 case '\\':
4143 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004144 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004145 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004146 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004147 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004148 if (ch != '\n') {
4149 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004150 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004151 o_addchr(&dest, ch);
4152 nommu_addchr(&ctx.as_string, ch);
4153 /* Example: echo Hello \2>file
4154 * we need to know that word 2 is quoted */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004155 dest.has_quoted_part = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004156 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004157#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004158 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004159 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4160 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004161 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02004162#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004163 break;
4164 case '$':
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004165 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004166 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004167 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004168 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004169 }
Eric Andersen25f27032001-04-26 23:22:31 +00004170 break;
4171 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004172 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004173 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004174 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004175 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004176 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004177 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004178 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004179 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004180 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004181 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004182 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004183 }
Eric Andersen25f27032001-04-26 23:22:31 +00004184 break;
4185 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004186 dest.has_quoted_part = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004187 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004188 if (dest.o_assignment == NOT_ASSIGNMENT)
4189 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004190 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004191#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004192 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004193 unsigned pos;
4194
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004195 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4196 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004197 pos = dest.length;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004198 add_till_backquote(&dest, input);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004199# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004200 o_addstr(&ctx.as_string, dest.data + pos);
4201 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004202# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004203 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4204 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004205 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004206 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004207#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004208 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004209#if ENABLE_HUSH_CASE
4210 case_semi:
4211#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004212 if (done_word(&dest, &ctx)) {
4213 goto parse_error;
4214 }
4215 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004216#if ENABLE_HUSH_CASE
4217 /* Eat multiple semicolons, detect
4218 * whether it means something special */
4219 while (1) {
4220 ch = i_peek(input);
4221 if (ch != ';')
4222 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004223 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004224 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004225 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004226 ctx.ctx_dsemicolon = 1;
4227 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004228 break;
4229 }
4230 }
4231#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004232 new_cmd:
4233 /* We just finished a cmd. New one may start
4234 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004235 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004236 break;
4237 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004238 if (done_word(&dest, &ctx)) {
4239 goto parse_error;
4240 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004241 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004242 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004243 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004244 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004245 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004246 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004247 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004248 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004249 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004250 if (done_word(&dest, &ctx)) {
4251 goto parse_error;
4252 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004253#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004254 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004255 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004256#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004257 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004258 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004259 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004260 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004261 } else {
4262 /* we could pick up a file descriptor choice here
4263 * with redirect_opt_num(), but bash doesn't do it.
4264 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004265 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004266#if !BB_MMU
4267 o_reset_to_empty_unquoted(&ctx.as_string);
4268#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004269 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004270 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004271 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004272#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004273 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004274 if (ctx.ctx_res_w == RES_MATCH
4275 && ctx.command->argv == NULL /* not (word|(... */
4276 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004277 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004278 ) {
4279 continue;
4280 }
4281#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004282 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004283 if (parse_group(&dest, &ctx, input, ch) != 0) {
4284 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004285 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004286 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004287 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004288#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004289 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004290 goto case_semi;
4291#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004292 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004293 /* proper use of this character is caught by end_trigger:
4294 * if we see {, we call parse_group(..., end_trigger='}')
4295 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004296 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004297 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004298 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004299 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004300 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004301 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004302 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004303
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004304 parse_error:
4305 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004306 struct parse_context *pctx;
4307 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004308
4309 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004310 * Sample for finding leaks on syntax error recovery path.
4311 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004312 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004313 * Samples to catch leaks at execution:
4314 * while if (true | {true;}); then echo ok; fi; do break; done
4315 * 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 +00004316 */
4317 pctx = &ctx;
4318 do {
4319 /* Update pipe/command counts,
4320 * otherwise freeing may miss some */
4321 done_pipe(pctx, PIPE_SEQ);
4322 debug_printf_clean("freeing list %p from ctx %p\n",
4323 pctx->list_head, pctx);
4324 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004325 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004326 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004327#if !BB_MMU
4328 o_free_unsafe(&pctx->as_string);
4329#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004330 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004331 if (pctx != &ctx) {
4332 free(pctx);
4333 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004334 IF_HAS_KEYWORDS(pctx = p2;)
4335 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004336 /* Free text, clear all dest fields */
4337 o_free(&dest);
4338 /* If we are not in top-level parse, we return,
4339 * our caller will propagate error.
4340 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004341 if (end_trigger != ';') {
4342#if !BB_MMU
4343 if (pstring)
4344 *pstring = NULL;
4345#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004346 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004347 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004348 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004349 /* Discard cached input, force prompt */
4350 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004351 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004352 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004353 }
Eric Andersen25f27032001-04-26 23:22:31 +00004354}
4355
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004356
4357/*** Execution routines ***/
4358
4359/* Expansion can recurse, need forward decls: */
4360static char *expand_string_to_string(const char *str);
4361static int process_command_subs(o_string *dest, const char *s);
4362
4363/* expand_strvec_to_strvec() takes a list of strings, expands
4364 * all variable references within and returns a pointer to
4365 * a list of expanded strings, possibly with larger number
4366 * of strings. (Think VAR="a b"; echo $VAR).
4367 * This new list is allocated as a single malloc block.
4368 * NULL-terminated list of char* pointers is at the beginning of it,
4369 * followed by strings themself.
4370 * Caller can deallocate entire list by single free(list). */
4371
4372/* Store given string, finalizing the word and starting new one whenever
4373 * we encounter IFS char(s). This is used for expanding variable values.
4374 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4375static int expand_on_ifs(o_string *output, int n, const char *str)
4376{
4377 while (1) {
4378 int word_len = strcspn(str, G.ifs);
4379 if (word_len) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004380 if (output->o_escape)
4381 o_addqblock(output, str, word_len);
4382 else if (!output->o_glob)
4383 o_addblock(output, str, word_len);
4384 else /* if (!escape && glob) */ {
4385 /* Protect backslashes against globbing up :)
4386 * Example: "v='\*'; echo b$v"
4387 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004388 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004389 /*/ Why can't we do it easier? */
4390 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4391 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4392 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004393 str += word_len;
4394 }
4395 if (!*str) /* EOL - do not finalize word */
4396 break;
4397 o_addchr(output, '\0');
4398 debug_print_list("expand_on_ifs", output, n);
4399 n = o_save_ptr(output, n);
4400 str += strspn(str, G.ifs); /* skip ifs chars */
4401 }
4402 debug_print_list("expand_on_ifs[1]", output, n);
4403 return n;
4404}
4405
4406/* Helper to expand $((...)) and heredoc body. These act as if
4407 * they are in double quotes, with the exception that they are not :).
4408 * Just the rules are similar: "expand only $var and `cmd`"
4409 *
4410 * Returns malloced string.
4411 * As an optimization, we return NULL if expansion is not needed.
4412 */
4413static char *expand_pseudo_dquoted(const char *str)
4414{
4415 char *exp_str;
4416 struct in_str input;
4417 o_string dest = NULL_O_STRING;
4418
4419 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004420 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004421#if ENABLE_HUSH_TICK
4422 && !strchr(str, '`')
4423#endif
4424 ) {
4425 return NULL;
4426 }
4427
4428 /* We need to expand. Example:
4429 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4430 */
4431 setup_string_in_str(&input, str);
4432 parse_stream_dquoted(NULL, &dest, &input, EOF);
4433 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4434 exp_str = expand_string_to_string(dest.data);
4435 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4436 o_free_unsafe(&dest);
4437 return exp_str;
4438}
4439
4440#if ENABLE_SH_MATH_SUPPORT
4441static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
4442{
4443 arith_eval_hooks_t hooks;
4444 arith_t res;
4445 char *exp_str;
4446
4447 hooks.lookupvar = get_local_var_value;
4448 hooks.setvar = set_local_var_from_halves;
4449 hooks.endofname = endofname;
4450 exp_str = expand_pseudo_dquoted(arg);
4451 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
4452 free(exp_str);
4453 return res;
4454}
4455#endif
4456
4457#if ENABLE_HUSH_BASH_COMPAT
4458/* ${var/[/]pattern[/repl]} helpers */
4459static char *strstr_pattern(char *val, const char *pattern, int *size)
4460{
4461 while (1) {
4462 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4463 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4464 if (end) {
4465 *size = end - val;
4466 return val;
4467 }
4468 if (*val == '\0')
4469 return NULL;
4470 /* Optimization: if "*pat" did not match the start of "string",
4471 * we know that "tring", "ring" etc will not match too:
4472 */
4473 if (pattern[0] == '*')
4474 return NULL;
4475 val++;
4476 }
4477}
4478static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4479{
4480 char *result = NULL;
4481 unsigned res_len = 0;
4482 unsigned repl_len = strlen(repl);
4483
4484 while (1) {
4485 int size;
4486 char *s = strstr_pattern(val, pattern, &size);
4487 if (!s)
4488 break;
4489
4490 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4491 memcpy(result + res_len, val, s - val);
4492 res_len += s - val;
4493 strcpy(result + res_len, repl);
4494 res_len += repl_len;
4495 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4496
4497 val = s + size;
4498 if (exp_op == '/')
4499 break;
4500 }
4501 if (val[0] && result) {
4502 result = xrealloc(result, res_len + strlen(val) + 1);
4503 strcpy(result + res_len, val);
4504 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4505 }
4506 debug_printf_varexp("result:'%s'\n", result);
4507 return result;
4508}
4509#endif
4510
4511/* Helper:
4512 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4513 */
4514static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp, char first_ch)
4515{
4516 const char *val = NULL;
4517 char *to_be_freed = NULL;
4518 char *p = *pp;
4519 char *var;
4520 char first_char;
4521 char exp_op;
4522 char exp_save = exp_save; /* for compiler */
4523 char *exp_saveptr; /* points to expansion operator */
4524 char *exp_word = exp_word; /* for compiler */
4525
4526 var = arg;
4527 *p = '\0';
4528 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4529 first_char = arg[0] = first_ch & 0x7f;
4530 exp_op = 0;
4531
4532 if (first_char == '#' && arg[1] && !exp_saveptr) {
4533 /* handle length expansion ${#var} */
4534 var++;
4535 exp_op = 'L';
4536 } else {
4537 /* maybe handle parameter expansion */
4538 if (exp_saveptr /* if 2nd char is one of expansion operators */
4539 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4540 ) {
4541 /* ${?:0}, ${#[:]%0} etc */
4542 exp_saveptr = var + 1;
4543 } else {
4544 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4545 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4546 }
4547 exp_op = exp_save = *exp_saveptr;
4548 if (exp_op) {
4549 exp_word = exp_saveptr + 1;
4550 if (exp_op == ':') {
4551 exp_op = *exp_word++;
4552 if (ENABLE_HUSH_BASH_COMPAT
4553 && (exp_op == '\0' || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4554 ) {
4555 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4556 exp_op = ':';
4557 exp_word--;
4558 }
4559 }
4560 *exp_saveptr = '\0';
4561 } /* else: it's not an expansion op, but bare ${var} */
4562 }
4563
4564 /* lookup the variable in question */
4565 if (isdigit(var[0])) {
4566 /* parse_dollar() should have vetted var for us */
4567 int n = xatoi_positive(var);
4568 if (n < G.global_argc)
4569 val = G.global_argv[n];
4570 /* else val remains NULL: $N with too big N */
4571 } else {
4572 switch (var[0]) {
4573 case '$': /* pid */
4574 val = utoa(G.root_pid);
4575 break;
4576 case '!': /* bg pid */
4577 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4578 break;
4579 case '?': /* exitcode */
4580 val = utoa(G.last_exitcode);
4581 break;
4582 case '#': /* argc */
4583 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4584 break;
4585 default:
4586 val = get_local_var_value(var);
4587 }
4588 }
4589
4590 /* Handle any expansions */
4591 if (exp_op == 'L') {
4592 debug_printf_expand("expand: length(%s)=", val);
4593 val = utoa(val ? strlen(val) : 0);
4594 debug_printf_expand("%s\n", val);
4595 } else if (exp_op) {
4596 if (exp_op == '%' || exp_op == '#') {
4597 /* Standard-mandated substring removal ops:
4598 * ${parameter%word} - remove smallest suffix pattern
4599 * ${parameter%%word} - remove largest suffix pattern
4600 * ${parameter#word} - remove smallest prefix pattern
4601 * ${parameter##word} - remove largest prefix pattern
4602 *
4603 * Word is expanded to produce a glob pattern.
4604 * Then var's value is matched to it and matching part removed.
4605 */
4606 if (val && val[0]) {
4607 char *exp_exp_word;
4608 char *loc;
4609 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4610 if (exp_op == *exp_word) /* ## or %% */
4611 exp_word++;
4612//TODO: avoid xstrdup unless needed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004613// (see HACK ALERT below for an example)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004614 val = to_be_freed = xstrdup(val);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004615//TODO: fix expansion rules:
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004616 exp_exp_word = expand_pseudo_dquoted(exp_word);
4617 if (exp_exp_word)
4618 exp_word = exp_exp_word;
4619 loc = scan_and_match(to_be_freed, exp_word, scan_flags);
4620 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4621 // exp_op, to_be_freed, exp_word, loc);
4622 free(exp_exp_word);
4623 if (loc) { /* match was found */
4624 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4625 val = loc;
4626 else /* %[%] */
4627 *loc = '\0';
4628 }
4629 }
4630 }
4631#if ENABLE_HUSH_BASH_COMPAT
4632 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004633 /* It's ${var/[/]pattern[/repl]} thing.
4634 * Note that in encoded form it has TWO parts:
4635 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4636 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004637 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004638 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004639 if (val && val[0]) {
4640 /* It's ${var/[/]pattern[/repl]} thing */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004641 /*
4642 * Pattern is taken literally, while
4643 * repl should be de-backslased and globbed
4644 * by the usual expansion rules:
4645 * >az; >bz;
4646 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4647 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4648 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4649 * v='a bz'; echo ${v/a*z/\z} prints "z"
4650 * (note that a*z _pattern_ is never globbed!)
4651 */
4652//TODO: fix expansion rules:
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004653 char *pattern, *repl, *t;
4654 pattern = expand_pseudo_dquoted(exp_word);
4655 if (!pattern)
4656 pattern = xstrdup(exp_word);
4657 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4658 *p++ = SPECIAL_VAR_SYMBOL;
4659 exp_word = p;
4660 p = strchr(p, SPECIAL_VAR_SYMBOL);
4661 *p = '\0';
4662 repl = expand_pseudo_dquoted(exp_word);
4663 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4664 /* HACK ALERT. We depend here on the fact that
4665 * G.global_argv and results of utoa and get_local_var_value
4666 * are actually in writable memory:
4667 * replace_pattern momentarily stores NULs there. */
4668 t = (char*)val;
4669 to_be_freed = replace_pattern(t,
4670 pattern,
4671 (repl ? repl : exp_word),
4672 exp_op);
4673 if (to_be_freed) /* at least one replace happened */
4674 val = to_be_freed;
4675 free(pattern);
4676 free(repl);
4677 }
4678 }
4679#endif
4680 else if (exp_op == ':') {
4681#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4682 /* It's ${var:N[:M]} bashism.
4683 * Note that in encoded form it has TWO parts:
4684 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4685 */
4686 arith_t beg, len;
4687 int errcode = 0;
4688
4689 beg = expand_and_evaluate_arith(exp_word, &errcode);
4690 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4691 *p++ = SPECIAL_VAR_SYMBOL;
4692 exp_word = p;
4693 p = strchr(p, SPECIAL_VAR_SYMBOL);
4694 *p = '\0';
4695 len = expand_and_evaluate_arith(exp_word, &errcode);
4696 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4697
4698 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
4699 if (beg < 0) /* bash compat */
4700 beg = 0;
4701 debug_printf_varexp("from val:'%s'\n", val);
4702 if (len == 0 || !val || beg >= strlen(val))
4703 val = "";
4704 else {
4705 /* Paranoia. What if user entered 9999999999999
4706 * which fits in arith_t but not int? */
4707 if (len >= INT_MAX)
4708 len = INT_MAX;
4709 val = to_be_freed = xstrndup(val + beg, len);
4710 }
4711 debug_printf_varexp("val:'%s'\n", val);
4712 } else
4713#endif
4714 {
4715 die_if_script("malformed ${%s:...}", var);
4716 val = "";
4717 }
4718 } else { /* one of "-=+?" */
4719 /* Standard-mandated substitution ops:
4720 * ${var?word} - indicate error if unset
4721 * If var is unset, word (or a message indicating it is unset
4722 * if word is null) is written to standard error
4723 * and the shell exits with a non-zero exit status.
4724 * Otherwise, the value of var is substituted.
4725 * ${var-word} - use default value
4726 * If var is unset, word is substituted.
4727 * ${var=word} - assign and use default value
4728 * If var is unset, word is assigned to var.
4729 * In all cases, final value of var is substituted.
4730 * ${var+word} - use alternative value
4731 * If var is unset, null is substituted.
4732 * Otherwise, word is substituted.
4733 *
4734 * Word is subjected to tilde expansion, parameter expansion,
4735 * command substitution, and arithmetic expansion.
4736 * If word is not needed, it is not expanded.
4737 *
4738 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4739 * but also treat null var as if it is unset.
4740 */
4741 int use_word = (!val || ((exp_save == ':') && !val[0]));
4742 if (exp_op == '+')
4743 use_word = !use_word;
4744 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4745 (exp_save == ':') ? "true" : "false", use_word);
4746 if (use_word) {
4747 to_be_freed = expand_pseudo_dquoted(exp_word);
4748 if (to_be_freed)
4749 exp_word = to_be_freed;
4750 if (exp_op == '?') {
4751 /* mimic bash message */
4752 die_if_script("%s: %s",
4753 var,
4754 exp_word[0] ? exp_word : "parameter null or not set"
4755 );
4756//TODO: how interactive bash aborts expansion mid-command?
4757 } else {
4758 val = exp_word;
4759 }
4760
4761 if (exp_op == '=') {
4762 /* ${var=[word]} or ${var:=[word]} */
4763 if (isdigit(var[0]) || var[0] == '#') {
4764 /* mimic bash message */
4765 die_if_script("$%s: cannot assign in this way", var);
4766 val = NULL;
4767 } else {
4768 char *new_var = xasprintf("%s=%s", var, val);
4769 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4770 }
4771 }
4772 }
4773 } /* one of "-=+?" */
4774
4775 *exp_saveptr = exp_save;
4776 } /* if (exp_op) */
4777
4778 arg[0] = first_ch;
4779
4780 *pp = p;
4781 *to_be_freed_pp = to_be_freed;
4782 return val;
4783}
4784
4785/* Expand all variable references in given string, adding words to list[]
4786 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4787 * to be filled). This routine is extremely tricky: has to deal with
4788 * variables/parameters with whitespace, $* and $@, and constructs like
4789 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4790static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
4791{
4792 /* or_mask is either 0 (normal case) or 0x80 -
4793 * expansion of right-hand side of assignment == 1-element expand.
4794 * It will also do no globbing, and thus we must not backslash-quote!
4795 */
4796 char ored_ch;
4797 char *p;
4798
4799 ored_ch = 0;
4800
4801 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
4802 debug_print_list("expand_vars_to_list", output, n);
4803 n = o_save_ptr(output, n);
4804 debug_print_list("expand_vars_to_list[0]", output, n);
4805
4806 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4807 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004808 char *to_be_freed = NULL;
4809 const char *val = NULL;
4810#if ENABLE_HUSH_TICK
4811 o_string subst_result = NULL_O_STRING;
4812#endif
4813#if ENABLE_SH_MATH_SUPPORT
4814 char arith_buf[sizeof(arith_t)*3 + 2];
4815#endif
4816 o_addblock(output, arg, p - arg);
4817 debug_print_list("expand_vars_to_list[1]", output, n);
4818 arg = ++p;
4819 p = strchr(p, SPECIAL_VAR_SYMBOL);
4820
4821 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
4822 /* "$@" is special. Even if quoted, it can still
4823 * expand to nothing (not even an empty string) */
4824 if ((first_ch & 0x7f) != '@')
4825 ored_ch |= first_ch;
4826
4827 switch (first_ch & 0x7f) {
4828 /* Highest bit in first_ch indicates that var is double-quoted */
4829 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004830 case '@': {
4831 int i;
4832 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004833 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004834 i = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004835 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4836 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4837 smallint sv = output->o_escape;
4838 /* unquoted var's contents should be globbed, so don't escape */
4839 output->o_escape = 0;
4840 while (G.global_argv[i]) {
4841 n = expand_on_ifs(output, n, G.global_argv[i]);
4842 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4843 if (G.global_argv[i++][0] && G.global_argv[i]) {
4844 /* this argv[] is not empty and not last:
4845 * put terminating NUL, start new word */
4846 o_addchr(output, '\0');
4847 debug_print_list("expand_vars_to_list[2]", output, n);
4848 n = o_save_ptr(output, n);
4849 debug_print_list("expand_vars_to_list[3]", output, n);
4850 }
4851 }
4852 output->o_escape = sv;
4853 } else
4854 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
4855 * and in this case should treat it like '$*' - see 'else...' below */
4856 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
4857 while (1) {
4858 o_addQstr(output, G.global_argv[i]);
4859 if (++i >= G.global_argc)
4860 break;
4861 o_addchr(output, '\0');
4862 debug_print_list("expand_vars_to_list[4]", output, n);
4863 n = o_save_ptr(output, n);
4864 }
4865 } else { /* quoted $*: add as one word */
4866 while (1) {
4867 o_addQstr(output, G.global_argv[i]);
4868 if (!G.global_argv[++i])
4869 break;
4870 if (G.ifs[0])
4871 o_addchr(output, G.ifs[0]);
4872 }
4873 }
4874 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004875 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004876 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4877 /* "Empty variable", used to make "" etc to not disappear */
4878 arg++;
4879 ored_ch = 0x80;
4880 break;
4881#if ENABLE_HUSH_TICK
4882 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4883 *p = '\0';
4884 arg++;
4885 /* Can't just stuff it into output o_string,
4886 * expanded result may need to be globbed
4887 * and $IFS-splitted */
4888 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4889 G.last_exitcode = process_command_subs(&subst_result, arg);
4890 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4891 val = subst_result.data;
4892 goto store_val;
4893#endif
4894#if ENABLE_SH_MATH_SUPPORT
4895 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4896 arith_t res;
4897 int errcode;
4898
4899 arg++; /* skip '+' */
4900 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4901 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4902 res = expand_and_evaluate_arith(arg, &errcode);
4903
4904 if (errcode < 0) {
4905 const char *msg = "error in arithmetic";
4906 switch (errcode) {
4907 case -3:
4908 msg = "exponent less than 0";
4909 break;
4910 case -2:
4911 msg = "divide by 0";
4912 break;
4913 case -5:
4914 msg = "expression recursion loop detected";
4915 break;
4916 }
4917 die_if_script(msg);
4918 }
4919 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
4920 sprintf(arith_buf, arith_t_fmt, res);
4921 val = arith_buf;
4922 break;
4923 }
4924#endif
4925 default:
4926 val = expand_one_var(&to_be_freed, arg, &p, first_ch);
4927 IF_HUSH_TICK(store_val:)
4928 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4929 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
4930 if (val && val[0]) {
4931 /* unquoted var's contents should be globbed, so don't escape */
4932 smallint sv = output->o_escape;
4933 output->o_escape = 0;
4934 n = expand_on_ifs(output, n, val);
4935 val = NULL;
4936 output->o_escape = sv;
4937 }
4938 } else { /* quoted $VAR, val will be appended below */
4939 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
4940 }
4941 break;
4942
4943 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4944
4945 if (val && val[0]) {
4946 o_addQstr(output, val);
4947 }
4948 free(to_be_freed);
4949 /* Do the check to avoid writing to a const string */
4950 if (*p != SPECIAL_VAR_SYMBOL)
4951 *p = SPECIAL_VAR_SYMBOL;
4952
4953#if ENABLE_HUSH_TICK
4954 o_free(&subst_result);
4955#endif
4956 arg = ++p;
4957 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4958
4959 if (arg[0]) {
4960 debug_print_list("expand_vars_to_list[a]", output, n);
4961 /* this part is literal, and it was already pre-quoted
4962 * if needed (much earlier), do not use o_addQstr here! */
4963 o_addstr_with_NUL(output, arg);
4964 debug_print_list("expand_vars_to_list[b]", output, n);
4965 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
4966 && !(ored_ch & 0x80) /* and all vars were not quoted. */
4967 ) {
4968 n--;
4969 /* allow to reuse list[n] later without re-growth */
4970 output->has_empty_slot = 1;
4971 } else {
4972 o_addchr(output, '\0');
4973 }
4974
4975 return n;
4976}
4977
4978enum {
4979 EXPVAR_FLAG_GLOB = 0x200,
4980 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
4981 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
4982};
4983static char **expand_variables(char **argv, unsigned or_mask)
4984{
4985 int n;
4986 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004987 o_string output = NULL_O_STRING;
4988
4989 /* protect against globbing for "$var"? */
4990 /* (unquoted $var will temporarily switch it off) */
4991 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
4992 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
4993
4994 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02004995 while (*argv) {
4996 n = expand_vars_to_list(&output, n, *argv, (unsigned char)or_mask);
4997 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004998 }
4999 debug_print_list("expand_variables", &output, n);
5000
5001 /* output.data (malloced in one block) gets returned in "list" */
5002 list = o_finalize_list(&output, n);
5003 debug_print_strings("expand_variables[1]", list);
5004 return list;
5005}
5006
5007static char **expand_strvec_to_strvec(char **argv)
5008{
5009 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
5010}
5011
5012#if ENABLE_HUSH_BASH_COMPAT
5013static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5014{
5015 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
5016}
5017#endif
5018
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005019/* Used for expansion of right hand of assignments */
5020/* NB: should NOT do globbing!
5021 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
5022static char *expand_string_to_string(const char *str)
5023{
5024 char *argv[2], **list;
5025
5026 /* This is generally an optimization, but it also
5027 * handles "", which otherwise trips over !list[0] check below.
5028 * (is this ever happens that we actually get str="" here?)
5029 */
5030 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5031 //TODO: Can use on strings with \ too, just unbackslash() them?
5032 debug_printf_expand("string_to_string(fast)='%s'\n", str);
5033 return xstrdup(str);
5034 }
5035
5036 argv[0] = (char*)str;
5037 argv[1] = NULL;
5038 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
5039 if (HUSH_DEBUG)
5040 if (!list[0] || list[1])
5041 bb_error_msg_and_die("BUG in varexp2");
5042 /* actually, just move string 2*sizeof(char*) bytes back */
5043 overlapping_strcpy((char*)list, list[0]);
5044 unbackslash((char*)list);
5045 debug_printf_expand("string_to_string='%s'\n", (char*)list);
5046 return (char*)list;
5047}
5048
5049/* Used for "eval" builtin */
5050static char* expand_strvec_to_string(char **argv)
5051{
5052 char **list;
5053
5054 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
5055 /* Convert all NULs to spaces */
5056 if (list[0]) {
5057 int n = 1;
5058 while (list[n]) {
5059 if (HUSH_DEBUG)
5060 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5061 bb_error_msg_and_die("BUG in varexp3");
5062 /* bash uses ' ' regardless of $IFS contents */
5063 list[n][-1] = ' ';
5064 n++;
5065 }
5066 }
5067 overlapping_strcpy((char*)list, list[0]);
5068 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5069 return (char*)list;
5070}
5071
5072static char **expand_assignments(char **argv, int count)
5073{
5074 int i;
5075 char **p;
5076
5077 G.expanded_assignments = p = NULL;
5078 /* Expand assignments into one string each */
5079 for (i = 0; i < count; i++) {
5080 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
5081 }
5082 G.expanded_assignments = NULL;
5083 return p;
5084}
5085
5086
5087#if BB_MMU
5088/* never called */
5089void re_execute_shell(char ***to_free, const char *s,
5090 char *g_argv0, char **g_argv,
5091 char **builtin_argv) NORETURN;
5092
5093static void reset_traps_to_defaults(void)
5094{
5095 /* This function is always called in a child shell
5096 * after fork (not vfork, NOMMU doesn't use this function).
5097 */
5098 unsigned sig;
5099 unsigned mask;
5100
5101 /* Child shells are not interactive.
5102 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5103 * Testcase: (while :; do :; done) + ^Z should background.
5104 * Same goes for SIGTERM, SIGHUP, SIGINT.
5105 */
5106 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5107 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5108
5109 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5110 * Stupid. It can be done with *single* &= op, but we can't use
5111 * the fact that G.blocked_set is implemented as a bitmask
5112 * in libc... */
5113 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5114 sig = 1;
5115 while (1) {
5116 if (mask & 1) {
5117 /* Careful. Only if no trap or trap is not "" */
5118 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5119 sigdelset(&G.blocked_set, sig);
5120 }
5121 mask >>= 1;
5122 if (!mask)
5123 break;
5124 sig++;
5125 }
5126 /* Our homegrown sig mask is saner to work with :) */
5127 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5128
5129 /* Resetting all traps to default except empty ones */
5130 mask = G.non_DFL_mask;
5131 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5132 if (!G.traps[sig] || !G.traps[sig][0])
5133 continue;
5134 free(G.traps[sig]);
5135 G.traps[sig] = NULL;
5136 /* There is no signal for 0 (EXIT) */
5137 if (sig == 0)
5138 continue;
5139 /* There was a trap handler, we just removed it.
5140 * But if sig still has non-DFL handling,
5141 * we should not unblock the sig. */
5142 if (mask & 1)
5143 continue;
5144 sigdelset(&G.blocked_set, sig);
5145 }
5146 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5147}
5148
5149#else /* !BB_MMU */
5150
5151static void re_execute_shell(char ***to_free, const char *s,
5152 char *g_argv0, char **g_argv,
5153 char **builtin_argv) NORETURN;
5154static void re_execute_shell(char ***to_free, const char *s,
5155 char *g_argv0, char **g_argv,
5156 char **builtin_argv)
5157{
5158# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5159 /* delims + 2 * (number of bytes in printed hex numbers) */
5160 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5161 char *heredoc_argv[4];
5162 struct variable *cur;
5163# if ENABLE_HUSH_FUNCTIONS
5164 struct function *funcp;
5165# endif
5166 char **argv, **pp;
5167 unsigned cnt;
5168 unsigned long long empty_trap_mask;
5169
5170 if (!g_argv0) { /* heredoc */
5171 argv = heredoc_argv;
5172 argv[0] = (char *) G.argv0_for_re_execing;
5173 argv[1] = (char *) "-<";
5174 argv[2] = (char *) s;
5175 argv[3] = NULL;
5176 pp = &argv[3]; /* used as pointer to empty environment */
5177 goto do_exec;
5178 }
5179
5180 cnt = 0;
5181 pp = builtin_argv;
5182 if (pp) while (*pp++)
5183 cnt++;
5184
5185 empty_trap_mask = 0;
5186 if (G.traps) {
5187 int sig;
5188 for (sig = 1; sig < NSIG; sig++) {
5189 if (G.traps[sig] && !G.traps[sig][0])
5190 empty_trap_mask |= 1LL << sig;
5191 }
5192 }
5193
5194 sprintf(param_buf, NOMMU_HACK_FMT
5195 , (unsigned) G.root_pid
5196 , (unsigned) G.root_ppid
5197 , (unsigned) G.last_bg_pid
5198 , (unsigned) G.last_exitcode
5199 , cnt
5200 , empty_trap_mask
5201 IF_HUSH_LOOPS(, G.depth_of_loop)
5202 );
5203# undef NOMMU_HACK_FMT
5204 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5205 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5206 */
5207 cnt += 6;
5208 for (cur = G.top_var; cur; cur = cur->next) {
5209 if (!cur->flg_export || cur->flg_read_only)
5210 cnt += 2;
5211 }
5212# if ENABLE_HUSH_FUNCTIONS
5213 for (funcp = G.top_func; funcp; funcp = funcp->next)
5214 cnt += 3;
5215# endif
5216 pp = g_argv;
5217 while (*pp++)
5218 cnt++;
5219 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5220 *pp++ = (char *) G.argv0_for_re_execing;
5221 *pp++ = param_buf;
5222 for (cur = G.top_var; cur; cur = cur->next) {
5223 if (strcmp(cur->varstr, hush_version_str) == 0)
5224 continue;
5225 if (cur->flg_read_only) {
5226 *pp++ = (char *) "-R";
5227 *pp++ = cur->varstr;
5228 } else if (!cur->flg_export) {
5229 *pp++ = (char *) "-V";
5230 *pp++ = cur->varstr;
5231 }
5232 }
5233# if ENABLE_HUSH_FUNCTIONS
5234 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5235 *pp++ = (char *) "-F";
5236 *pp++ = funcp->name;
5237 *pp++ = funcp->body_as_string;
5238 }
5239# endif
5240 /* We can pass activated traps here. Say, -Tnn:trap_string
5241 *
5242 * However, POSIX says that subshells reset signals with traps
5243 * to SIG_DFL.
5244 * I tested bash-3.2 and it not only does that with true subshells
5245 * of the form ( list ), but with any forked children shells.
5246 * I set trap "echo W" WINCH; and then tried:
5247 *
5248 * { echo 1; sleep 20; echo 2; } &
5249 * while true; do echo 1; sleep 20; echo 2; break; done &
5250 * true | { echo 1; sleep 20; echo 2; } | cat
5251 *
5252 * In all these cases sending SIGWINCH to the child shell
5253 * did not run the trap. If I add trap "echo V" WINCH;
5254 * _inside_ group (just before echo 1), it works.
5255 *
5256 * I conclude it means we don't need to pass active traps here.
5257 * Even if we would use signal handlers instead of signal masking
5258 * in order to implement trap handling,
5259 * exec syscall below resets signals to SIG_DFL for us.
5260 */
5261 *pp++ = (char *) "-c";
5262 *pp++ = (char *) s;
5263 if (builtin_argv) {
5264 while (*++builtin_argv)
5265 *pp++ = *builtin_argv;
5266 *pp++ = (char *) "";
5267 }
5268 *pp++ = g_argv0;
5269 while (*g_argv)
5270 *pp++ = *g_argv++;
5271 /* *pp = NULL; - is already there */
5272 pp = environ;
5273
5274 do_exec:
5275 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5276 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5277 execve(bb_busybox_exec_path, argv, pp);
5278 /* Fallback. Useful for init=/bin/hush usage etc */
5279 if (argv[0][0] == '/')
5280 execve(argv[0], argv, pp);
5281 xfunc_error_retval = 127;
5282 bb_error_msg_and_die("can't re-execute the shell");
5283}
5284#endif /* !BB_MMU */
5285
5286
5287static int run_and_free_list(struct pipe *pi);
5288
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005289/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005290 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5291 * end_trigger controls how often we stop parsing
5292 * NUL: parse all, execute, return
5293 * ';': parse till ';' or newline, execute, repeat till EOF
5294 */
5295static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005296{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005297 /* Why we need empty flag?
5298 * An obscure corner case "false; ``; echo $?":
5299 * empty command in `` should still set $? to 0.
5300 * But we can't just set $? to 0 at the start,
5301 * this breaks "false; echo `echo $?`" case.
5302 */
5303 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005304 while (1) {
5305 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005306
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005307 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005308 if (!pipe_list) { /* EOF */
5309 if (empty)
5310 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005311 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005312 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005313 debug_print_tree(pipe_list, 0);
5314 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5315 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005316 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005317 }
Eric Andersen25f27032001-04-26 23:22:31 +00005318}
5319
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005320static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005321{
5322 struct in_str input;
5323 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005324 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005325}
5326
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005327static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005328{
Eric Andersen25f27032001-04-26 23:22:31 +00005329 struct in_str input;
5330 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005331 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005332}
5333
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005334#if ENABLE_HUSH_TICK
5335static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5336{
5337 pid_t pid;
5338 int channel[2];
5339# if !BB_MMU
5340 char **to_free = NULL;
5341# endif
5342
5343 xpipe(channel);
5344 pid = BB_MMU ? xfork() : xvfork();
5345 if (pid == 0) { /* child */
5346 disable_restore_tty_pgrp_on_exit();
5347 /* Process substitution is not considered to be usual
5348 * 'command execution'.
5349 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5350 */
5351 bb_signals(0
5352 + (1 << SIGTSTP)
5353 + (1 << SIGTTIN)
5354 + (1 << SIGTTOU)
5355 , SIG_IGN);
5356 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5357 close(channel[0]); /* NB: close _first_, then move fd! */
5358 xmove_fd(channel[1], 1);
5359 /* Prevent it from trying to handle ctrl-z etc */
5360 IF_HUSH_JOB(G.run_list_level = 1;)
5361 /* Awful hack for `trap` or $(trap).
5362 *
5363 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5364 * contains an example where "trap" is executed in a subshell:
5365 *
5366 * save_traps=$(trap)
5367 * ...
5368 * eval "$save_traps"
5369 *
5370 * Standard does not say that "trap" in subshell shall print
5371 * parent shell's traps. It only says that its output
5372 * must have suitable form, but then, in the above example
5373 * (which is not supposed to be normative), it implies that.
5374 *
5375 * bash (and probably other shell) does implement it
5376 * (traps are reset to defaults, but "trap" still shows them),
5377 * but as a result, "trap" logic is hopelessly messed up:
5378 *
5379 * # trap
5380 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5381 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5382 * # true | trap <--- trap is in subshell - no output (ditto)
5383 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5384 * trap -- 'echo Ho' SIGWINCH
5385 * # echo `(trap)` <--- in subshell in subshell - output
5386 * trap -- 'echo Ho' SIGWINCH
5387 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5388 * trap -- 'echo Ho' SIGWINCH
5389 *
5390 * The rules when to forget and when to not forget traps
5391 * get really complex and nonsensical.
5392 *
5393 * Our solution: ONLY bare $(trap) or `trap` is special.
5394 */
5395 s = skip_whitespace(s);
5396 if (strncmp(s, "trap", 4) == 0
5397 && skip_whitespace(s + 4)[0] == '\0'
5398 ) {
5399 static const char *const argv[] = { NULL, NULL };
5400 builtin_trap((char**)argv);
5401 exit(0); /* not _exit() - we need to fflush */
5402 }
5403# if BB_MMU
5404 reset_traps_to_defaults();
5405 parse_and_run_string(s);
5406 _exit(G.last_exitcode);
5407# else
5408 /* We re-execute after vfork on NOMMU. This makes this script safe:
5409 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5410 * huge=`cat BIG` # was blocking here forever
5411 * echo OK
5412 */
5413 re_execute_shell(&to_free,
5414 s,
5415 G.global_argv[0],
5416 G.global_argv + 1,
5417 NULL);
5418# endif
5419 }
5420
5421 /* parent */
5422 *pid_p = pid;
5423# if ENABLE_HUSH_FAST
5424 G.count_SIGCHLD++;
5425//bb_error_msg("[%d] fork in generate_stream_from_string:"
5426// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5427// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5428# endif
5429 enable_restore_tty_pgrp_on_exit();
5430# if !BB_MMU
5431 free(to_free);
5432# endif
5433 close(channel[1]);
5434 close_on_exec_on(channel[0]);
5435 return xfdopen_for_read(channel[0]);
5436}
5437
5438/* Return code is exit status of the process that is run. */
5439static int process_command_subs(o_string *dest, const char *s)
5440{
5441 FILE *fp;
5442 struct in_str pipe_str;
5443 pid_t pid;
5444 int status, ch, eol_cnt;
5445
5446 fp = generate_stream_from_string(s, &pid);
5447
5448 /* Now send results of command back into original context */
5449 setup_file_in_str(&pipe_str, fp);
5450 eol_cnt = 0;
5451 while ((ch = i_getch(&pipe_str)) != EOF) {
5452 if (ch == '\n') {
5453 eol_cnt++;
5454 continue;
5455 }
5456 while (eol_cnt) {
5457 o_addchr(dest, '\n');
5458 eol_cnt--;
5459 }
5460 o_addQchr(dest, ch);
5461 }
5462
5463 debug_printf("done reading from `cmd` pipe, closing it\n");
5464 fclose(fp);
5465 /* We need to extract exitcode. Test case
5466 * "true; echo `sleep 1; false` $?"
5467 * should print 1 */
5468 safe_waitpid(pid, &status, 0);
5469 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5470 return WEXITSTATUS(status);
5471}
5472#endif /* ENABLE_HUSH_TICK */
5473
5474
5475static void setup_heredoc(struct redir_struct *redir)
5476{
5477 struct fd_pair pair;
5478 pid_t pid;
5479 int len, written;
5480 /* the _body_ of heredoc (misleading field name) */
5481 const char *heredoc = redir->rd_filename;
5482 char *expanded;
5483#if !BB_MMU
5484 char **to_free;
5485#endif
5486
5487 expanded = NULL;
5488 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5489 expanded = expand_pseudo_dquoted(heredoc);
5490 if (expanded)
5491 heredoc = expanded;
5492 }
5493 len = strlen(heredoc);
5494
5495 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5496 xpiped_pair(pair);
5497 xmove_fd(pair.rd, redir->rd_fd);
5498
5499 /* Try writing without forking. Newer kernels have
5500 * dynamically growing pipes. Must use non-blocking write! */
5501 ndelay_on(pair.wr);
5502 while (1) {
5503 written = write(pair.wr, heredoc, len);
5504 if (written <= 0)
5505 break;
5506 len -= written;
5507 if (len == 0) {
5508 close(pair.wr);
5509 free(expanded);
5510 return;
5511 }
5512 heredoc += written;
5513 }
5514 ndelay_off(pair.wr);
5515
5516 /* Okay, pipe buffer was not big enough */
5517 /* Note: we must not create a stray child (bastard? :)
5518 * for the unsuspecting parent process. Child creates a grandchild
5519 * and exits before parent execs the process which consumes heredoc
5520 * (that exec happens after we return from this function) */
5521#if !BB_MMU
5522 to_free = NULL;
5523#endif
5524 pid = xvfork();
5525 if (pid == 0) {
5526 /* child */
5527 disable_restore_tty_pgrp_on_exit();
5528 pid = BB_MMU ? xfork() : xvfork();
5529 if (pid != 0)
5530 _exit(0);
5531 /* grandchild */
5532 close(redir->rd_fd); /* read side of the pipe */
5533#if BB_MMU
5534 full_write(pair.wr, heredoc, len); /* may loop or block */
5535 _exit(0);
5536#else
5537 /* Delegate blocking writes to another process */
5538 xmove_fd(pair.wr, STDOUT_FILENO);
5539 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5540#endif
5541 }
5542 /* parent */
5543#if ENABLE_HUSH_FAST
5544 G.count_SIGCHLD++;
5545//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5546#endif
5547 enable_restore_tty_pgrp_on_exit();
5548#if !BB_MMU
5549 free(to_free);
5550#endif
5551 close(pair.wr);
5552 free(expanded);
5553 wait(NULL); /* wait till child has died */
5554}
5555
5556/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5557 * and stderr if they are redirected. */
5558static int setup_redirects(struct command *prog, int squirrel[])
5559{
5560 int openfd, mode;
5561 struct redir_struct *redir;
5562
5563 for (redir = prog->redirects; redir; redir = redir->next) {
5564 if (redir->rd_type == REDIRECT_HEREDOC2) {
5565 /* rd_fd<<HERE case */
5566 if (squirrel && redir->rd_fd < 3
5567 && squirrel[redir->rd_fd] < 0
5568 ) {
5569 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5570 }
5571 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5572 * of the heredoc */
5573 debug_printf_parse("set heredoc '%s'\n",
5574 redir->rd_filename);
5575 setup_heredoc(redir);
5576 continue;
5577 }
5578
5579 if (redir->rd_dup == REDIRFD_TO_FILE) {
5580 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5581 char *p;
5582 if (redir->rd_filename == NULL) {
5583 /* Something went wrong in the parse.
5584 * Pretend it didn't happen */
5585 bb_error_msg("bug in redirect parse");
5586 continue;
5587 }
5588 mode = redir_table[redir->rd_type].mode;
5589 p = expand_string_to_string(redir->rd_filename);
5590 openfd = open_or_warn(p, mode);
5591 free(p);
5592 if (openfd < 0) {
5593 /* this could get lost if stderr has been redirected, but
5594 * bash and ash both lose it as well (though zsh doesn't!) */
5595//what the above comment tries to say?
5596 return 1;
5597 }
5598 } else {
5599 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5600 openfd = redir->rd_dup;
5601 }
5602
5603 if (openfd != redir->rd_fd) {
5604 if (squirrel && redir->rd_fd < 3
5605 && squirrel[redir->rd_fd] < 0
5606 ) {
5607 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5608 }
5609 if (openfd == REDIRFD_CLOSE) {
5610 /* "n>-" means "close me" */
5611 close(redir->rd_fd);
5612 } else {
5613 xdup2(openfd, redir->rd_fd);
5614 if (redir->rd_dup == REDIRFD_TO_FILE)
5615 close(openfd);
5616 }
5617 }
5618 }
5619 return 0;
5620}
5621
5622static void restore_redirects(int squirrel[])
5623{
5624 int i, fd;
5625 for (i = 0; i < 3; i++) {
5626 fd = squirrel[i];
5627 if (fd != -1) {
5628 /* We simply die on error */
5629 xmove_fd(fd, i);
5630 }
5631 }
5632}
5633
5634static char *find_in_path(const char *arg)
5635{
5636 char *ret = NULL;
5637 const char *PATH = get_local_var_value("PATH");
5638
5639 if (!PATH)
5640 return NULL;
5641
5642 while (1) {
5643 const char *end = strchrnul(PATH, ':');
5644 int sz = end - PATH; /* must be int! */
5645
5646 free(ret);
5647 if (sz != 0) {
5648 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5649 } else {
5650 /* We have xxx::yyyy in $PATH,
5651 * it means "use current dir" */
5652 ret = xstrdup(arg);
5653 }
5654 if (access(ret, F_OK) == 0)
5655 break;
5656
5657 if (*end == '\0') {
5658 free(ret);
5659 return NULL;
5660 }
5661 PATH = end + 1;
5662 }
5663
5664 return ret;
5665}
5666
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005667static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005668 const struct built_in_command *x,
5669 const struct built_in_command *end)
5670{
5671 while (x != end) {
5672 if (strcmp(name, x->b_cmd) != 0) {
5673 x++;
5674 continue;
5675 }
5676 debug_printf_exec("found builtin '%s'\n", name);
5677 return x;
5678 }
5679 return NULL;
5680}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005681static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005682{
5683 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5684}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005685static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005686{
5687 const struct built_in_command *x = find_builtin1(name);
5688 if (x)
5689 return x;
5690 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5691}
5692
5693#if ENABLE_HUSH_FUNCTIONS
5694static struct function **find_function_slot(const char *name)
5695{
5696 struct function **funcpp = &G.top_func;
5697 while (*funcpp) {
5698 if (strcmp(name, (*funcpp)->name) == 0) {
5699 break;
5700 }
5701 funcpp = &(*funcpp)->next;
5702 }
5703 return funcpp;
5704}
5705
5706static const struct function *find_function(const char *name)
5707{
5708 const struct function *funcp = *find_function_slot(name);
5709 if (funcp)
5710 debug_printf_exec("found function '%s'\n", name);
5711 return funcp;
5712}
5713
5714/* Note: takes ownership on name ptr */
5715static struct function *new_function(char *name)
5716{
5717 struct function **funcpp = find_function_slot(name);
5718 struct function *funcp = *funcpp;
5719
5720 if (funcp != NULL) {
5721 struct command *cmd = funcp->parent_cmd;
5722 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5723 if (!cmd) {
5724 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5725 free(funcp->name);
5726 /* Note: if !funcp->body, do not free body_as_string!
5727 * This is a special case of "-F name body" function:
5728 * body_as_string was not malloced! */
5729 if (funcp->body) {
5730 free_pipe_list(funcp->body);
5731# if !BB_MMU
5732 free(funcp->body_as_string);
5733# endif
5734 }
5735 } else {
5736 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5737 cmd->argv[0] = funcp->name;
5738 cmd->group = funcp->body;
5739# if !BB_MMU
5740 cmd->group_as_string = funcp->body_as_string;
5741# endif
5742 }
5743 } else {
5744 debug_printf_exec("remembering new function '%s'\n", name);
5745 funcp = *funcpp = xzalloc(sizeof(*funcp));
5746 /*funcp->next = NULL;*/
5747 }
5748
5749 funcp->name = name;
5750 return funcp;
5751}
5752
5753static void unset_func(const char *name)
5754{
5755 struct function **funcpp = find_function_slot(name);
5756 struct function *funcp = *funcpp;
5757
5758 if (funcp != NULL) {
5759 debug_printf_exec("freeing function '%s'\n", funcp->name);
5760 *funcpp = funcp->next;
5761 /* funcp is unlinked now, deleting it.
5762 * Note: if !funcp->body, the function was created by
5763 * "-F name body", do not free ->body_as_string
5764 * and ->name as they were not malloced. */
5765 if (funcp->body) {
5766 free_pipe_list(funcp->body);
5767 free(funcp->name);
5768# if !BB_MMU
5769 free(funcp->body_as_string);
5770# endif
5771 }
5772 free(funcp);
5773 }
5774}
5775
5776# if BB_MMU
5777#define exec_function(to_free, funcp, argv) \
5778 exec_function(funcp, argv)
5779# endif
5780static void exec_function(char ***to_free,
5781 const struct function *funcp,
5782 char **argv) NORETURN;
5783static void exec_function(char ***to_free,
5784 const struct function *funcp,
5785 char **argv)
5786{
5787# if BB_MMU
5788 int n = 1;
5789
5790 argv[0] = G.global_argv[0];
5791 G.global_argv = argv;
5792 while (*++argv)
5793 n++;
5794 G.global_argc = n;
5795 /* On MMU, funcp->body is always non-NULL */
5796 n = run_list(funcp->body);
5797 fflush_all();
5798 _exit(n);
5799# else
5800 re_execute_shell(to_free,
5801 funcp->body_as_string,
5802 G.global_argv[0],
5803 argv + 1,
5804 NULL);
5805# endif
5806}
5807
5808static int run_function(const struct function *funcp, char **argv)
5809{
5810 int rc;
5811 save_arg_t sv;
5812 smallint sv_flg;
5813
5814 save_and_replace_G_args(&sv, argv);
5815
5816 /* "we are in function, ok to use return" */
5817 sv_flg = G.flag_return_in_progress;
5818 G.flag_return_in_progress = -1;
5819# if ENABLE_HUSH_LOCAL
5820 G.func_nest_level++;
5821# endif
5822
5823 /* On MMU, funcp->body is always non-NULL */
5824# if !BB_MMU
5825 if (!funcp->body) {
5826 /* Function defined by -F */
5827 parse_and_run_string(funcp->body_as_string);
5828 rc = G.last_exitcode;
5829 } else
5830# endif
5831 {
5832 rc = run_list(funcp->body);
5833 }
5834
5835# if ENABLE_HUSH_LOCAL
5836 {
5837 struct variable *var;
5838 struct variable **var_pp;
5839
5840 var_pp = &G.top_var;
5841 while ((var = *var_pp) != NULL) {
5842 if (var->func_nest_level < G.func_nest_level) {
5843 var_pp = &var->next;
5844 continue;
5845 }
5846 /* Unexport */
5847 if (var->flg_export)
5848 bb_unsetenv(var->varstr);
5849 /* Remove from global list */
5850 *var_pp = var->next;
5851 /* Free */
5852 if (!var->max_len)
5853 free(var->varstr);
5854 free(var);
5855 }
5856 G.func_nest_level--;
5857 }
5858# endif
5859 G.flag_return_in_progress = sv_flg;
5860
5861 restore_G_args(&sv, argv);
5862
5863 return rc;
5864}
5865#endif /* ENABLE_HUSH_FUNCTIONS */
5866
5867
5868#if BB_MMU
5869#define exec_builtin(to_free, x, argv) \
5870 exec_builtin(x, argv)
5871#else
5872#define exec_builtin(to_free, x, argv) \
5873 exec_builtin(to_free, argv)
5874#endif
5875static void exec_builtin(char ***to_free,
5876 const struct built_in_command *x,
5877 char **argv) NORETURN;
5878static void exec_builtin(char ***to_free,
5879 const struct built_in_command *x,
5880 char **argv)
5881{
5882#if BB_MMU
5883 int rcode = x->b_function(argv);
5884 fflush_all();
5885 _exit(rcode);
5886#else
5887 /* On NOMMU, we must never block!
5888 * Example: { sleep 99 | read line; } & echo Ok
5889 */
5890 re_execute_shell(to_free,
5891 argv[0],
5892 G.global_argv[0],
5893 G.global_argv + 1,
5894 argv);
5895#endif
5896}
5897
5898
5899static void execvp_or_die(char **argv) NORETURN;
5900static void execvp_or_die(char **argv)
5901{
5902 debug_printf_exec("execing '%s'\n", argv[0]);
5903 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5904 execvp(argv[0], argv);
5905 bb_perror_msg("can't execute '%s'", argv[0]);
5906 _exit(127); /* bash compat */
5907}
5908
5909#if ENABLE_HUSH_MODE_X
5910static void dump_cmd_in_x_mode(char **argv)
5911{
5912 if (G_x_mode && argv) {
5913 /* We want to output the line in one write op */
5914 char *buf, *p;
5915 int len;
5916 int n;
5917
5918 len = 3;
5919 n = 0;
5920 while (argv[n])
5921 len += strlen(argv[n++]) + 1;
5922 buf = xmalloc(len);
5923 buf[0] = '+';
5924 p = buf + 1;
5925 n = 0;
5926 while (argv[n])
5927 p += sprintf(p, " %s", argv[n++]);
5928 *p++ = '\n';
5929 *p = '\0';
5930 fputs(buf, stderr);
5931 free(buf);
5932 }
5933}
5934#else
5935# define dump_cmd_in_x_mode(argv) ((void)0)
5936#endif
5937
5938#if BB_MMU
5939#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5940 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5941#define pseudo_exec(nommu_save, command, argv_expanded) \
5942 pseudo_exec(command, argv_expanded)
5943#endif
5944
5945/* Called after [v]fork() in run_pipe, or from builtin_exec.
5946 * Never returns.
5947 * Don't exit() here. If you don't exec, use _exit instead.
5948 * The at_exit handlers apparently confuse the calling process,
5949 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5950static void pseudo_exec_argv(nommu_save_t *nommu_save,
5951 char **argv, int assignment_cnt,
5952 char **argv_expanded) NORETURN;
5953static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5954 char **argv, int assignment_cnt,
5955 char **argv_expanded)
5956{
5957 char **new_env;
5958
5959 new_env = expand_assignments(argv, assignment_cnt);
5960 dump_cmd_in_x_mode(new_env);
5961
5962 if (!argv[assignment_cnt]) {
5963 /* Case when we are here: ... | var=val | ...
5964 * (note that we do not exit early, i.e., do not optimize out
5965 * expand_assignments(): think about ... | var=`sleep 1` | ...
5966 */
5967 free_strings(new_env);
5968 _exit(EXIT_SUCCESS);
5969 }
5970
5971#if BB_MMU
5972 set_vars_and_save_old(new_env);
5973 free(new_env); /* optional */
5974 /* we can also destroy set_vars_and_save_old's return value,
5975 * to save memory */
5976#else
5977 nommu_save->new_env = new_env;
5978 nommu_save->old_vars = set_vars_and_save_old(new_env);
5979#endif
5980
5981 if (argv_expanded) {
5982 argv = argv_expanded;
5983 } else {
5984 argv = expand_strvec_to_strvec(argv + assignment_cnt);
5985#if !BB_MMU
5986 nommu_save->argv = argv;
5987#endif
5988 }
5989 dump_cmd_in_x_mode(argv);
5990
5991#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
5992 if (strchr(argv[0], '/') != NULL)
5993 goto skip;
5994#endif
5995
5996 /* Check if the command matches any of the builtins.
5997 * Depending on context, this might be redundant. But it's
5998 * easier to waste a few CPU cycles than it is to figure out
5999 * if this is one of those cases.
6000 */
6001 {
6002 /* On NOMMU, it is more expensive to re-execute shell
6003 * just in order to run echo or test builtin.
6004 * It's better to skip it here and run corresponding
6005 * non-builtin later. */
6006 const struct built_in_command *x;
6007 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6008 if (x) {
6009 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6010 }
6011 }
6012#if ENABLE_HUSH_FUNCTIONS
6013 /* Check if the command matches any functions */
6014 {
6015 const struct function *funcp = find_function(argv[0]);
6016 if (funcp) {
6017 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6018 }
6019 }
6020#endif
6021
6022#if ENABLE_FEATURE_SH_STANDALONE
6023 /* Check if the command matches any busybox applets */
6024 {
6025 int a = find_applet_by_name(argv[0]);
6026 if (a >= 0) {
6027# if BB_MMU /* see above why on NOMMU it is not allowed */
6028 if (APPLET_IS_NOEXEC(a)) {
6029 debug_printf_exec("running applet '%s'\n", argv[0]);
6030 run_applet_no_and_exit(a, argv);
6031 }
6032# endif
6033 /* Re-exec ourselves */
6034 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6035 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6036 execv(bb_busybox_exec_path, argv);
6037 /* If they called chroot or otherwise made the binary no longer
6038 * executable, fall through */
6039 }
6040 }
6041#endif
6042
6043#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6044 skip:
6045#endif
6046 execvp_or_die(argv);
6047}
6048
6049/* Called after [v]fork() in run_pipe
6050 */
6051static void pseudo_exec(nommu_save_t *nommu_save,
6052 struct command *command,
6053 char **argv_expanded) NORETURN;
6054static void pseudo_exec(nommu_save_t *nommu_save,
6055 struct command *command,
6056 char **argv_expanded)
6057{
6058 if (command->argv) {
6059 pseudo_exec_argv(nommu_save, command->argv,
6060 command->assignment_cnt, argv_expanded);
6061 }
6062
6063 if (command->group) {
6064 /* Cases when we are here:
6065 * ( list )
6066 * { list } &
6067 * ... | ( list ) | ...
6068 * ... | { list } | ...
6069 */
6070#if BB_MMU
6071 int rcode;
6072 debug_printf_exec("pseudo_exec: run_list\n");
6073 reset_traps_to_defaults();
6074 rcode = run_list(command->group);
6075 /* OK to leak memory by not calling free_pipe_list,
6076 * since this process is about to exit */
6077 _exit(rcode);
6078#else
6079 re_execute_shell(&nommu_save->argv_from_re_execing,
6080 command->group_as_string,
6081 G.global_argv[0],
6082 G.global_argv + 1,
6083 NULL);
6084#endif
6085 }
6086
6087 /* Case when we are here: ... | >file */
6088 debug_printf_exec("pseudo_exec'ed null command\n");
6089 _exit(EXIT_SUCCESS);
6090}
6091
6092#if ENABLE_HUSH_JOB
6093static const char *get_cmdtext(struct pipe *pi)
6094{
6095 char **argv;
6096 char *p;
6097 int len;
6098
6099 /* This is subtle. ->cmdtext is created only on first backgrounding.
6100 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6101 * On subsequent bg argv is trashed, but we won't use it */
6102 if (pi->cmdtext)
6103 return pi->cmdtext;
6104 argv = pi->cmds[0].argv;
6105 if (!argv || !argv[0]) {
6106 pi->cmdtext = xzalloc(1);
6107 return pi->cmdtext;
6108 }
6109
6110 len = 0;
6111 do {
6112 len += strlen(*argv) + 1;
6113 } while (*++argv);
6114 p = xmalloc(len);
6115 pi->cmdtext = p;
6116 argv = pi->cmds[0].argv;
6117 do {
6118 len = strlen(*argv);
6119 memcpy(p, *argv, len);
6120 p += len;
6121 *p++ = ' ';
6122 } while (*++argv);
6123 p[-1] = '\0';
6124 return pi->cmdtext;
6125}
6126
6127static void insert_bg_job(struct pipe *pi)
6128{
6129 struct pipe *job, **jobp;
6130 int i;
6131
6132 /* Linear search for the ID of the job to use */
6133 pi->jobid = 1;
6134 for (job = G.job_list; job; job = job->next)
6135 if (job->jobid >= pi->jobid)
6136 pi->jobid = job->jobid + 1;
6137
6138 /* Add job to the list of running jobs */
6139 jobp = &G.job_list;
6140 while ((job = *jobp) != NULL)
6141 jobp = &job->next;
6142 job = *jobp = xmalloc(sizeof(*job));
6143
6144 *job = *pi; /* physical copy */
6145 job->next = NULL;
6146 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6147 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6148 for (i = 0; i < pi->num_cmds; i++) {
6149 job->cmds[i].pid = pi->cmds[i].pid;
6150 /* all other fields are not used and stay zero */
6151 }
6152 job->cmdtext = xstrdup(get_cmdtext(pi));
6153
6154 if (G_interactive_fd)
6155 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6156 G.last_jobid = job->jobid;
6157}
6158
6159static void remove_bg_job(struct pipe *pi)
6160{
6161 struct pipe *prev_pipe;
6162
6163 if (pi == G.job_list) {
6164 G.job_list = pi->next;
6165 } else {
6166 prev_pipe = G.job_list;
6167 while (prev_pipe->next != pi)
6168 prev_pipe = prev_pipe->next;
6169 prev_pipe->next = pi->next;
6170 }
6171 if (G.job_list)
6172 G.last_jobid = G.job_list->jobid;
6173 else
6174 G.last_jobid = 0;
6175}
6176
6177/* Remove a backgrounded job */
6178static void delete_finished_bg_job(struct pipe *pi)
6179{
6180 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006181 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006182}
6183#endif /* JOB */
6184
6185/* Check to see if any processes have exited -- if they
6186 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006187static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006188{
6189 int attributes;
6190 int status;
6191#if ENABLE_HUSH_JOB
6192 struct pipe *pi;
6193#endif
6194 pid_t childpid;
6195 int rcode = 0;
6196
6197 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6198
6199 attributes = WUNTRACED;
6200 if (fg_pipe == NULL)
6201 attributes |= WNOHANG;
6202
6203 errno = 0;
6204#if ENABLE_HUSH_FAST
6205 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6206//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6207//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6208 /* There was neither fork nor SIGCHLD since last waitpid */
6209 /* Avoid doing waitpid syscall if possible */
6210 if (!G.we_have_children) {
6211 errno = ECHILD;
6212 return -1;
6213 }
6214 if (fg_pipe == NULL) { /* is WNOHANG set? */
6215 /* We have children, but they did not exit
6216 * or stop yet (we saw no SIGCHLD) */
6217 return 0;
6218 }
6219 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6220 }
6221#endif
6222
6223/* Do we do this right?
6224 * bash-3.00# sleep 20 | false
6225 * <ctrl-Z pressed>
6226 * [3]+ Stopped sleep 20 | false
6227 * bash-3.00# echo $?
6228 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6229 * [hush 1.14.0: yes we do it right]
6230 */
6231 wait_more:
6232 while (1) {
6233 int i;
6234 int dead;
6235
6236#if ENABLE_HUSH_FAST
6237 i = G.count_SIGCHLD;
6238#endif
6239 childpid = waitpid(-1, &status, attributes);
6240 if (childpid <= 0) {
6241 if (childpid && errno != ECHILD)
6242 bb_perror_msg("waitpid");
6243#if ENABLE_HUSH_FAST
6244 else { /* Until next SIGCHLD, waitpid's are useless */
6245 G.we_have_children = (childpid == 0);
6246 G.handled_SIGCHLD = i;
6247//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6248 }
6249#endif
6250 break;
6251 }
6252 dead = WIFEXITED(status) || WIFSIGNALED(status);
6253
6254#if DEBUG_JOBS
6255 if (WIFSTOPPED(status))
6256 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6257 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6258 if (WIFSIGNALED(status))
6259 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6260 childpid, WTERMSIG(status), WEXITSTATUS(status));
6261 if (WIFEXITED(status))
6262 debug_printf_jobs("pid %d exited, exitcode %d\n",
6263 childpid, WEXITSTATUS(status));
6264#endif
6265 /* Were we asked to wait for fg pipe? */
6266 if (fg_pipe) {
6267 for (i = 0; i < fg_pipe->num_cmds; i++) {
6268 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6269 if (fg_pipe->cmds[i].pid != childpid)
6270 continue;
6271 if (dead) {
6272 fg_pipe->cmds[i].pid = 0;
6273 fg_pipe->alive_cmds--;
6274 if (i == fg_pipe->num_cmds - 1) {
6275 /* last process gives overall exitstatus */
6276 rcode = WEXITSTATUS(status);
6277 /* bash prints killer signal's name for *last*
6278 * process in pipe (prints just newline for SIGINT).
6279 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6280 */
6281 if (WIFSIGNALED(status)) {
6282 int sig = WTERMSIG(status);
6283 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6284 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6285 * Maybe we need to use sig | 128? */
6286 rcode = sig + 128;
6287 }
6288 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6289 }
6290 } else {
6291 fg_pipe->cmds[i].is_stopped = 1;
6292 fg_pipe->stopped_cmds++;
6293 }
6294 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6295 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6296 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6297 /* All processes in fg pipe have exited or stopped */
6298/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6299 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6300 * and "killall -STOP cat" */
6301 if (G_interactive_fd) {
6302#if ENABLE_HUSH_JOB
6303 if (fg_pipe->alive_cmds)
6304 insert_bg_job(fg_pipe);
6305#endif
6306 return rcode;
6307 }
6308 if (!fg_pipe->alive_cmds)
6309 return rcode;
6310 }
6311 /* There are still running processes in the fg pipe */
6312 goto wait_more; /* do waitpid again */
6313 }
6314 /* it wasnt fg_pipe, look for process in bg pipes */
6315 }
6316
6317#if ENABLE_HUSH_JOB
6318 /* We asked to wait for bg or orphaned children */
6319 /* No need to remember exitcode in this case */
6320 for (pi = G.job_list; pi; pi = pi->next) {
6321 for (i = 0; i < pi->num_cmds; i++) {
6322 if (pi->cmds[i].pid == childpid)
6323 goto found_pi_and_prognum;
6324 }
6325 }
6326 /* Happens when shell is used as init process (init=/bin/sh) */
6327 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6328 continue; /* do waitpid again */
6329
6330 found_pi_and_prognum:
6331 if (dead) {
6332 /* child exited */
6333 pi->cmds[i].pid = 0;
6334 pi->alive_cmds--;
6335 if (!pi->alive_cmds) {
6336 if (G_interactive_fd)
6337 printf(JOB_STATUS_FORMAT, pi->jobid,
6338 "Done", pi->cmdtext);
6339 delete_finished_bg_job(pi);
6340 }
6341 } else {
6342 /* child stopped */
6343 pi->cmds[i].is_stopped = 1;
6344 pi->stopped_cmds++;
6345 }
6346#endif
6347 } /* while (waitpid succeeds)... */
6348
6349 return rcode;
6350}
6351
6352#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006353static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006354{
6355 pid_t p;
6356 int rcode = checkjobs(fg_pipe);
6357 if (G_saved_tty_pgrp) {
6358 /* Job finished, move the shell to the foreground */
6359 p = getpgrp(); /* our process group id */
6360 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6361 tcsetpgrp(G_interactive_fd, p);
6362 }
6363 return rcode;
6364}
6365#endif
6366
6367/* Start all the jobs, but don't wait for anything to finish.
6368 * See checkjobs().
6369 *
6370 * Return code is normally -1, when the caller has to wait for children
6371 * to finish to determine the exit status of the pipe. If the pipe
6372 * is a simple builtin command, however, the action is done by the
6373 * time run_pipe returns, and the exit code is provided as the
6374 * return value.
6375 *
6376 * Returns -1 only if started some children. IOW: we have to
6377 * mask out retvals of builtins etc with 0xff!
6378 *
6379 * The only case when we do not need to [v]fork is when the pipe
6380 * is single, non-backgrounded, non-subshell command. Examples:
6381 * cmd ; ... { list } ; ...
6382 * cmd && ... { list } && ...
6383 * cmd || ... { list } || ...
6384 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6385 * or (if SH_STANDALONE) an applet, and we can run the { list }
6386 * with run_list. If it isn't one of these, we fork and exec cmd.
6387 *
6388 * Cases when we must fork:
6389 * non-single: cmd | cmd
6390 * backgrounded: cmd & { list } &
6391 * subshell: ( list ) [&]
6392 */
6393#if !ENABLE_HUSH_MODE_X
6394#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6395 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6396#endif
6397static int redirect_and_varexp_helper(char ***new_env_p,
6398 struct variable **old_vars_p,
6399 struct command *command,
6400 int squirrel[3],
6401 char **argv_expanded)
6402{
6403 /* setup_redirects acts on file descriptors, not FILEs.
6404 * This is perfect for work that comes after exec().
6405 * Is it really safe for inline use? Experimentally,
6406 * things seem to work. */
6407 int rcode = setup_redirects(command, squirrel);
6408 if (rcode == 0) {
6409 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6410 *new_env_p = new_env;
6411 dump_cmd_in_x_mode(new_env);
6412 dump_cmd_in_x_mode(argv_expanded);
6413 if (old_vars_p)
6414 *old_vars_p = set_vars_and_save_old(new_env);
6415 }
6416 return rcode;
6417}
6418static NOINLINE int run_pipe(struct pipe *pi)
6419{
6420 static const char *const null_ptr = NULL;
6421
6422 int cmd_no;
6423 int next_infd;
6424 struct command *command;
6425 char **argv_expanded;
6426 char **argv;
6427 /* it is not always needed, but we aim to smaller code */
6428 int squirrel[] = { -1, -1, -1 };
6429 int rcode;
6430
6431 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6432 debug_enter();
6433
6434 IF_HUSH_JOB(pi->pgrp = -1;)
6435 pi->stopped_cmds = 0;
6436 command = &pi->cmds[0];
6437 argv_expanded = NULL;
6438
6439 if (pi->num_cmds != 1
6440 || pi->followup == PIPE_BG
6441 || command->cmd_type == CMD_SUBSHELL
6442 ) {
6443 goto must_fork;
6444 }
6445
6446 pi->alive_cmds = 1;
6447
6448 debug_printf_exec(": group:%p argv:'%s'\n",
6449 command->group, command->argv ? command->argv[0] : "NONE");
6450
6451 if (command->group) {
6452#if ENABLE_HUSH_FUNCTIONS
6453 if (command->cmd_type == CMD_FUNCDEF) {
6454 /* "executing" func () { list } */
6455 struct function *funcp;
6456
6457 funcp = new_function(command->argv[0]);
6458 /* funcp->name is already set to argv[0] */
6459 funcp->body = command->group;
6460# if !BB_MMU
6461 funcp->body_as_string = command->group_as_string;
6462 command->group_as_string = NULL;
6463# endif
6464 command->group = NULL;
6465 command->argv[0] = NULL;
6466 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6467 funcp->parent_cmd = command;
6468 command->child_func = funcp;
6469
6470 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6471 debug_leave();
6472 return EXIT_SUCCESS;
6473 }
6474#endif
6475 /* { list } */
6476 debug_printf("non-subshell group\n");
6477 rcode = 1; /* exitcode if redir failed */
6478 if (setup_redirects(command, squirrel) == 0) {
6479 debug_printf_exec(": run_list\n");
6480 rcode = run_list(command->group) & 0xff;
6481 }
6482 restore_redirects(squirrel);
6483 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6484 debug_leave();
6485 debug_printf_exec("run_pipe: return %d\n", rcode);
6486 return rcode;
6487 }
6488
6489 argv = command->argv ? command->argv : (char **) &null_ptr;
6490 {
6491 const struct built_in_command *x;
6492#if ENABLE_HUSH_FUNCTIONS
6493 const struct function *funcp;
6494#else
6495 enum { funcp = 0 };
6496#endif
6497 char **new_env = NULL;
6498 struct variable *old_vars = NULL;
6499
6500 if (argv[command->assignment_cnt] == NULL) {
6501 /* Assignments, but no command */
6502 /* Ensure redirects take effect (that is, create files).
6503 * Try "a=t >file" */
6504#if 0 /* A few cases in testsuite fail with this code. FIXME */
6505 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6506 /* Set shell variables */
6507 if (new_env) {
6508 argv = new_env;
6509 while (*argv) {
6510 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6511 /* Do we need to flag set_local_var() errors?
6512 * "assignment to readonly var" and "putenv error"
6513 */
6514 argv++;
6515 }
6516 }
6517 /* Redirect error sets $? to 1. Otherwise,
6518 * if evaluating assignment value set $?, retain it.
6519 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6520 if (rcode == 0)
6521 rcode = G.last_exitcode;
6522 /* Exit, _skipping_ variable restoring code: */
6523 goto clean_up_and_ret0;
6524
6525#else /* Older, bigger, but more correct code */
6526
6527 rcode = setup_redirects(command, squirrel);
6528 restore_redirects(squirrel);
6529 /* Set shell variables */
6530 if (G_x_mode)
6531 bb_putchar_stderr('+');
6532 while (*argv) {
6533 char *p = expand_string_to_string(*argv);
6534 if (G_x_mode)
6535 fprintf(stderr, " %s", p);
6536 debug_printf_exec("set shell var:'%s'->'%s'\n",
6537 *argv, p);
6538 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6539 /* Do we need to flag set_local_var() errors?
6540 * "assignment to readonly var" and "putenv error"
6541 */
6542 argv++;
6543 }
6544 if (G_x_mode)
6545 bb_putchar_stderr('\n');
6546 /* Redirect error sets $? to 1. Otherwise,
6547 * if evaluating assignment value set $?, retain it.
6548 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6549 if (rcode == 0)
6550 rcode = G.last_exitcode;
6551 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6552 debug_leave();
6553 debug_printf_exec("run_pipe: return %d\n", rcode);
6554 return rcode;
6555#endif
6556 }
6557
6558 /* Expand the rest into (possibly) many strings each */
6559 if (0) {}
6560#if ENABLE_HUSH_BASH_COMPAT
6561 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6562 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6563 }
6564#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006565 else {
6566 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6567 }
6568
6569 /* if someone gives us an empty string: `cmd with empty output` */
6570 if (!argv_expanded[0]) {
6571 free(argv_expanded);
6572 debug_leave();
6573 return G.last_exitcode;
6574 }
6575
6576 x = find_builtin(argv_expanded[0]);
6577#if ENABLE_HUSH_FUNCTIONS
6578 funcp = NULL;
6579 if (!x)
6580 funcp = find_function(argv_expanded[0]);
6581#endif
6582 if (x || funcp) {
6583 if (!funcp) {
6584 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6585 debug_printf("exec with redirects only\n");
6586 rcode = setup_redirects(command, NULL);
6587 goto clean_up_and_ret1;
6588 }
6589 }
6590 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6591 if (rcode == 0) {
6592 if (!funcp) {
6593 debug_printf_exec(": builtin '%s' '%s'...\n",
6594 x->b_cmd, argv_expanded[1]);
6595 rcode = x->b_function(argv_expanded) & 0xff;
6596 fflush_all();
6597 }
6598#if ENABLE_HUSH_FUNCTIONS
6599 else {
6600# if ENABLE_HUSH_LOCAL
6601 struct variable **sv;
6602 sv = G.shadowed_vars_pp;
6603 G.shadowed_vars_pp = &old_vars;
6604# endif
6605 debug_printf_exec(": function '%s' '%s'...\n",
6606 funcp->name, argv_expanded[1]);
6607 rcode = run_function(funcp, argv_expanded) & 0xff;
6608# if ENABLE_HUSH_LOCAL
6609 G.shadowed_vars_pp = sv;
6610# endif
6611 }
6612#endif
6613 }
6614 clean_up_and_ret:
6615 unset_vars(new_env);
6616 add_vars(old_vars);
6617/* clean_up_and_ret0: */
6618 restore_redirects(squirrel);
6619 clean_up_and_ret1:
6620 free(argv_expanded);
6621 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6622 debug_leave();
6623 debug_printf_exec("run_pipe return %d\n", rcode);
6624 return rcode;
6625 }
6626
6627 if (ENABLE_FEATURE_SH_STANDALONE) {
6628 int n = find_applet_by_name(argv_expanded[0]);
6629 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6630 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6631 if (rcode == 0) {
6632 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6633 argv_expanded[0], argv_expanded[1]);
6634 rcode = run_nofork_applet(n, argv_expanded);
6635 }
6636 goto clean_up_and_ret;
6637 }
6638 }
6639 /* It is neither builtin nor applet. We must fork. */
6640 }
6641
6642 must_fork:
6643 /* NB: argv_expanded may already be created, and that
6644 * might include `cmd` runs! Do not rerun it! We *must*
6645 * use argv_expanded if it's non-NULL */
6646
6647 /* Going to fork a child per each pipe member */
6648 pi->alive_cmds = 0;
6649 next_infd = 0;
6650
6651 cmd_no = 0;
6652 while (cmd_no < pi->num_cmds) {
6653 struct fd_pair pipefds;
6654#if !BB_MMU
6655 volatile nommu_save_t nommu_save;
6656 nommu_save.new_env = NULL;
6657 nommu_save.old_vars = NULL;
6658 nommu_save.argv = NULL;
6659 nommu_save.argv_from_re_execing = NULL;
6660#endif
6661 command = &pi->cmds[cmd_no];
6662 cmd_no++;
6663 if (command->argv) {
6664 debug_printf_exec(": pipe member '%s' '%s'...\n",
6665 command->argv[0], command->argv[1]);
6666 } else {
6667 debug_printf_exec(": pipe member with no argv\n");
6668 }
6669
6670 /* pipes are inserted between pairs of commands */
6671 pipefds.rd = 0;
6672 pipefds.wr = 1;
6673 if (cmd_no < pi->num_cmds)
6674 xpiped_pair(pipefds);
6675
6676 command->pid = BB_MMU ? fork() : vfork();
6677 if (!command->pid) { /* child */
6678#if ENABLE_HUSH_JOB
6679 disable_restore_tty_pgrp_on_exit();
6680 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6681
6682 /* Every child adds itself to new process group
6683 * with pgid == pid_of_first_child_in_pipe */
6684 if (G.run_list_level == 1 && G_interactive_fd) {
6685 pid_t pgrp;
6686 pgrp = pi->pgrp;
6687 if (pgrp < 0) /* true for 1st process only */
6688 pgrp = getpid();
6689 if (setpgid(0, pgrp) == 0
6690 && pi->followup != PIPE_BG
6691 && G_saved_tty_pgrp /* we have ctty */
6692 ) {
6693 /* We do it in *every* child, not just first,
6694 * to avoid races */
6695 tcsetpgrp(G_interactive_fd, pgrp);
6696 }
6697 }
6698#endif
6699 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6700 /* 1st cmd in backgrounded pipe
6701 * should have its stdin /dev/null'ed */
6702 close(0);
6703 if (open(bb_dev_null, O_RDONLY))
6704 xopen("/", O_RDONLY);
6705 } else {
6706 xmove_fd(next_infd, 0);
6707 }
6708 xmove_fd(pipefds.wr, 1);
6709 if (pipefds.rd > 1)
6710 close(pipefds.rd);
6711 /* Like bash, explicit redirects override pipes,
6712 * and the pipe fd is available for dup'ing. */
6713 if (setup_redirects(command, NULL))
6714 _exit(1);
6715
6716 /* Restore default handlers just prior to exec */
6717 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6718
6719 /* Stores to nommu_save list of env vars putenv'ed
6720 * (NOMMU, on MMU we don't need that) */
6721 /* cast away volatility... */
6722 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6723 /* pseudo_exec() does not return */
6724 }
6725
6726 /* parent or error */
6727#if ENABLE_HUSH_FAST
6728 G.count_SIGCHLD++;
6729//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6730#endif
6731 enable_restore_tty_pgrp_on_exit();
6732#if !BB_MMU
6733 /* Clean up after vforked child */
6734 free(nommu_save.argv);
6735 free(nommu_save.argv_from_re_execing);
6736 unset_vars(nommu_save.new_env);
6737 add_vars(nommu_save.old_vars);
6738#endif
6739 free(argv_expanded);
6740 argv_expanded = NULL;
6741 if (command->pid < 0) { /* [v]fork failed */
6742 /* Clearly indicate, was it fork or vfork */
6743 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6744 } else {
6745 pi->alive_cmds++;
6746#if ENABLE_HUSH_JOB
6747 /* Second and next children need to know pid of first one */
6748 if (pi->pgrp < 0)
6749 pi->pgrp = command->pid;
6750#endif
6751 }
6752
6753 if (cmd_no > 1)
6754 close(next_infd);
6755 if (cmd_no < pi->num_cmds)
6756 close(pipefds.wr);
6757 /* Pass read (output) pipe end to next iteration */
6758 next_infd = pipefds.rd;
6759 }
6760
6761 if (!pi->alive_cmds) {
6762 debug_leave();
6763 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6764 return 1;
6765 }
6766
6767 debug_leave();
6768 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6769 return -1;
6770}
6771
6772#ifndef debug_print_tree
6773static void debug_print_tree(struct pipe *pi, int lvl)
6774{
6775 static const char *const PIPE[] = {
6776 [PIPE_SEQ] = "SEQ",
6777 [PIPE_AND] = "AND",
6778 [PIPE_OR ] = "OR" ,
6779 [PIPE_BG ] = "BG" ,
6780 };
6781 static const char *RES[] = {
6782 [RES_NONE ] = "NONE" ,
6783# if ENABLE_HUSH_IF
6784 [RES_IF ] = "IF" ,
6785 [RES_THEN ] = "THEN" ,
6786 [RES_ELIF ] = "ELIF" ,
6787 [RES_ELSE ] = "ELSE" ,
6788 [RES_FI ] = "FI" ,
6789# endif
6790# if ENABLE_HUSH_LOOPS
6791 [RES_FOR ] = "FOR" ,
6792 [RES_WHILE] = "WHILE",
6793 [RES_UNTIL] = "UNTIL",
6794 [RES_DO ] = "DO" ,
6795 [RES_DONE ] = "DONE" ,
6796# endif
6797# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6798 [RES_IN ] = "IN" ,
6799# endif
6800# if ENABLE_HUSH_CASE
6801 [RES_CASE ] = "CASE" ,
6802 [RES_CASE_IN ] = "CASE_IN" ,
6803 [RES_MATCH] = "MATCH",
6804 [RES_CASE_BODY] = "CASE_BODY",
6805 [RES_ESAC ] = "ESAC" ,
6806# endif
6807 [RES_XXXX ] = "XXXX" ,
6808 [RES_SNTX ] = "SNTX" ,
6809 };
6810 static const char *const CMDTYPE[] = {
6811 "{}",
6812 "()",
6813 "[noglob]",
6814# if ENABLE_HUSH_FUNCTIONS
6815 "func()",
6816# endif
6817 };
6818
6819 int pin, prn;
6820
6821 pin = 0;
6822 while (pi) {
6823 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6824 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6825 prn = 0;
6826 while (prn < pi->num_cmds) {
6827 struct command *command = &pi->cmds[prn];
6828 char **argv = command->argv;
6829
6830 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6831 lvl*2, "", prn,
6832 command->assignment_cnt);
6833 if (command->group) {
6834 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6835 CMDTYPE[command->cmd_type],
6836 argv
6837# if !BB_MMU
6838 , " group_as_string:", command->group_as_string
6839# else
6840 , "", ""
6841# endif
6842 );
6843 debug_print_tree(command->group, lvl+1);
6844 prn++;
6845 continue;
6846 }
6847 if (argv) while (*argv) {
6848 fprintf(stderr, " '%s'", *argv);
6849 argv++;
6850 }
6851 fprintf(stderr, "\n");
6852 prn++;
6853 }
6854 pi = pi->next;
6855 pin++;
6856 }
6857}
6858#endif /* debug_print_tree */
6859
6860/* NB: called by pseudo_exec, and therefore must not modify any
6861 * global data until exec/_exit (we can be a child after vfork!) */
6862static int run_list(struct pipe *pi)
6863{
6864#if ENABLE_HUSH_CASE
6865 char *case_word = NULL;
6866#endif
6867#if ENABLE_HUSH_LOOPS
6868 struct pipe *loop_top = NULL;
6869 char **for_lcur = NULL;
6870 char **for_list = NULL;
6871#endif
6872 smallint last_followup;
6873 smalluint rcode;
6874#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6875 smalluint cond_code = 0;
6876#else
6877 enum { cond_code = 0 };
6878#endif
6879#if HAS_KEYWORDS
6880 smallint rword; /* enum reserved_style */
6881 smallint last_rword; /* ditto */
6882#endif
6883
6884 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6885 debug_enter();
6886
6887#if ENABLE_HUSH_LOOPS
6888 /* Check syntax for "for" */
6889 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6890 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6891 continue;
6892 /* current word is FOR or IN (BOLD in comments below) */
6893 if (cpipe->next == NULL) {
6894 syntax_error("malformed for");
6895 debug_leave();
6896 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6897 return 1;
6898 }
6899 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6900 if (cpipe->next->res_word == RES_DO)
6901 continue;
6902 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6903 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6904 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6905 ) {
6906 syntax_error("malformed for");
6907 debug_leave();
6908 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6909 return 1;
6910 }
6911 }
6912#endif
6913
6914 /* Past this point, all code paths should jump to ret: label
6915 * in order to return, no direct "return" statements please.
6916 * This helps to ensure that no memory is leaked. */
6917
6918#if ENABLE_HUSH_JOB
6919 G.run_list_level++;
6920#endif
6921
6922#if HAS_KEYWORDS
6923 rword = RES_NONE;
6924 last_rword = RES_XXXX;
6925#endif
6926 last_followup = PIPE_SEQ;
6927 rcode = G.last_exitcode;
6928
6929 /* Go through list of pipes, (maybe) executing them. */
6930 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6931 if (G.flag_SIGINT)
6932 break;
6933
6934 IF_HAS_KEYWORDS(rword = pi->res_word;)
6935 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6936 rword, cond_code, last_rword);
6937#if ENABLE_HUSH_LOOPS
6938 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6939 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6940 ) {
6941 /* start of a loop: remember where loop starts */
6942 loop_top = pi;
6943 G.depth_of_loop++;
6944 }
6945#endif
6946 /* Still in the same "if...", "then..." or "do..." branch? */
6947 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6948 if ((rcode == 0 && last_followup == PIPE_OR)
6949 || (rcode != 0 && last_followup == PIPE_AND)
6950 ) {
6951 /* It is "<true> || CMD" or "<false> && CMD"
6952 * and we should not execute CMD */
6953 debug_printf_exec("skipped cmd because of || or &&\n");
6954 last_followup = pi->followup;
6955 continue;
6956 }
6957 }
6958 last_followup = pi->followup;
6959 IF_HAS_KEYWORDS(last_rword = rword;)
6960#if ENABLE_HUSH_IF
6961 if (cond_code) {
6962 if (rword == RES_THEN) {
6963 /* if false; then ... fi has exitcode 0! */
6964 G.last_exitcode = rcode = EXIT_SUCCESS;
6965 /* "if <false> THEN cmd": skip cmd */
6966 continue;
6967 }
6968 } else {
6969 if (rword == RES_ELSE || rword == RES_ELIF) {
6970 /* "if <true> then ... ELSE/ELIF cmd":
6971 * skip cmd and all following ones */
6972 break;
6973 }
6974 }
6975#endif
6976#if ENABLE_HUSH_LOOPS
6977 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
6978 if (!for_lcur) {
6979 /* first loop through for */
6980
6981 static const char encoded_dollar_at[] ALIGN1 = {
6982 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
6983 }; /* encoded representation of "$@" */
6984 static const char *const encoded_dollar_at_argv[] = {
6985 encoded_dollar_at, NULL
6986 }; /* argv list with one element: "$@" */
6987 char **vals;
6988
6989 vals = (char**)encoded_dollar_at_argv;
6990 if (pi->next->res_word == RES_IN) {
6991 /* if no variable values after "in" we skip "for" */
6992 if (!pi->next->cmds[0].argv) {
6993 G.last_exitcode = rcode = EXIT_SUCCESS;
6994 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
6995 break;
6996 }
6997 vals = pi->next->cmds[0].argv;
6998 } /* else: "for var; do..." -> assume "$@" list */
6999 /* create list of variable values */
7000 debug_print_strings("for_list made from", vals);
7001 for_list = expand_strvec_to_strvec(vals);
7002 for_lcur = for_list;
7003 debug_print_strings("for_list", for_list);
7004 }
7005 if (!*for_lcur) {
7006 /* "for" loop is over, clean up */
7007 free(for_list);
7008 for_list = NULL;
7009 for_lcur = NULL;
7010 break;
7011 }
7012 /* Insert next value from for_lcur */
7013 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7014 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7015 continue;
7016 }
7017 if (rword == RES_IN) {
7018 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7019 }
7020 if (rword == RES_DONE) {
7021 continue; /* "done" has no cmds too */
7022 }
7023#endif
7024#if ENABLE_HUSH_CASE
7025 if (rword == RES_CASE) {
7026 case_word = expand_strvec_to_string(pi->cmds->argv);
7027 continue;
7028 }
7029 if (rword == RES_MATCH) {
7030 char **argv;
7031
7032 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7033 break;
7034 /* all prev words didn't match, does this one match? */
7035 argv = pi->cmds->argv;
7036 while (*argv) {
7037 char *pattern = expand_string_to_string(*argv);
7038 /* TODO: which FNM_xxx flags to use? */
7039 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7040 free(pattern);
7041 if (cond_code == 0) { /* match! we will execute this branch */
7042 free(case_word); /* make future "word)" stop */
7043 case_word = NULL;
7044 break;
7045 }
7046 argv++;
7047 }
7048 continue;
7049 }
7050 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7051 if (cond_code != 0)
7052 continue; /* not matched yet, skip this pipe */
7053 }
7054#endif
7055 /* Just pressing <enter> in shell should check for jobs.
7056 * OTOH, in non-interactive shell this is useless
7057 * and only leads to extra job checks */
7058 if (pi->num_cmds == 0) {
7059 if (G_interactive_fd)
7060 goto check_jobs_and_continue;
7061 continue;
7062 }
7063
7064 /* After analyzing all keywords and conditions, we decided
7065 * to execute this pipe. NB: have to do checkjobs(NULL)
7066 * after run_pipe to collect any background children,
7067 * even if list execution is to be stopped. */
7068 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7069 {
7070 int r;
7071#if ENABLE_HUSH_LOOPS
7072 G.flag_break_continue = 0;
7073#endif
7074 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7075 if (r != -1) {
7076 /* We ran a builtin, function, or group.
7077 * rcode is already known
7078 * and we don't need to wait for anything. */
7079 G.last_exitcode = rcode;
7080 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7081 check_and_run_traps(0);
7082#if ENABLE_HUSH_LOOPS
7083 /* Was it "break" or "continue"? */
7084 if (G.flag_break_continue) {
7085 smallint fbc = G.flag_break_continue;
7086 /* We might fall into outer *loop*,
7087 * don't want to break it too */
7088 if (loop_top) {
7089 G.depth_break_continue--;
7090 if (G.depth_break_continue == 0)
7091 G.flag_break_continue = 0;
7092 /* else: e.g. "continue 2" should *break* once, *then* continue */
7093 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7094 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7095 goto check_jobs_and_break;
7096 /* "continue": simulate end of loop */
7097 rword = RES_DONE;
7098 continue;
7099 }
7100#endif
7101#if ENABLE_HUSH_FUNCTIONS
7102 if (G.flag_return_in_progress == 1) {
7103 /* same as "goto check_jobs_and_break" */
7104 checkjobs(NULL);
7105 break;
7106 }
7107#endif
7108 } else if (pi->followup == PIPE_BG) {
7109 /* What does bash do with attempts to background builtins? */
7110 /* even bash 3.2 doesn't do that well with nested bg:
7111 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7112 * I'm NOT treating inner &'s as jobs */
7113 check_and_run_traps(0);
7114#if ENABLE_HUSH_JOB
7115 if (G.run_list_level == 1)
7116 insert_bg_job(pi);
7117#endif
7118 /* Last command's pid goes to $! */
7119 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7120 G.last_exitcode = rcode = EXIT_SUCCESS;
7121 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7122 } else {
7123#if ENABLE_HUSH_JOB
7124 if (G.run_list_level == 1 && G_interactive_fd) {
7125 /* Waits for completion, then fg's main shell */
7126 rcode = checkjobs_and_fg_shell(pi);
7127 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7128 check_and_run_traps(0);
7129 } else
7130#endif
7131 { /* This one just waits for completion */
7132 rcode = checkjobs(pi);
7133 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7134 check_and_run_traps(0);
7135 }
7136 G.last_exitcode = rcode;
7137 }
7138 }
7139
7140 /* Analyze how result affects subsequent commands */
7141#if ENABLE_HUSH_IF
7142 if (rword == RES_IF || rword == RES_ELIF)
7143 cond_code = rcode;
7144#endif
7145#if ENABLE_HUSH_LOOPS
7146 /* Beware of "while false; true; do ..."! */
7147 if (pi->next && pi->next->res_word == RES_DO) {
7148 if (rword == RES_WHILE) {
7149 if (rcode) {
7150 /* "while false; do...done" - exitcode 0 */
7151 G.last_exitcode = rcode = EXIT_SUCCESS;
7152 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7153 goto check_jobs_and_break;
7154 }
7155 }
7156 if (rword == RES_UNTIL) {
7157 if (!rcode) {
7158 debug_printf_exec(": until expr is true: breaking\n");
7159 check_jobs_and_break:
7160 checkjobs(NULL);
7161 break;
7162 }
7163 }
7164 }
7165#endif
7166
7167 check_jobs_and_continue:
7168 checkjobs(NULL);
7169 } /* for (pi) */
7170
7171#if ENABLE_HUSH_JOB
7172 G.run_list_level--;
7173#endif
7174#if ENABLE_HUSH_LOOPS
7175 if (loop_top)
7176 G.depth_of_loop--;
7177 free(for_list);
7178#endif
7179#if ENABLE_HUSH_CASE
7180 free(case_word);
7181#endif
7182 debug_leave();
7183 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7184 return rcode;
7185}
7186
7187/* Select which version we will use */
7188static int run_and_free_list(struct pipe *pi)
7189{
7190 int rcode = 0;
7191 debug_printf_exec("run_and_free_list entered\n");
7192 if (!G.n_mode) {
7193 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7194 rcode = run_list(pi);
7195 }
7196 /* free_pipe_list has the side effect of clearing memory.
7197 * In the long run that function can be merged with run_list,
7198 * but doing that now would hobble the debugging effort. */
7199 free_pipe_list(pi);
7200 debug_printf_exec("run_and_free_list return %d\n", rcode);
7201 return rcode;
7202}
7203
7204
Denis Vlasenkof9375282009-04-05 19:13:39 +00007205/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007206static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007207{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007208 unsigned sig;
7209 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007210 sigset_t old_blocked_set;
7211
7212 if (!G.inherited_set_is_saved) {
7213 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7214 G.inherited_set = G.blocked_set;
7215 }
7216 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007217
Denis Vlasenkof9375282009-04-05 19:13:39 +00007218 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007219 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007220 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007221 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007222 mask |= SPECIAL_JOB_SIGS;
7223 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007224 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007225
Denis Vlasenkof9375282009-04-05 19:13:39 +00007226 sig = 0;
7227 while (mask) {
7228 if (mask & 1)
7229 sigaddset(&G.blocked_set, sig);
7230 mask >>= 1;
7231 sig++;
7232 }
7233 sigdelset(&G.blocked_set, SIGCHLD);
7234
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007235 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7236 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7237
Denis Vlasenkof9375282009-04-05 19:13:39 +00007238 /* POSIX allows shell to re-enable SIGCHLD
7239 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007240#if ENABLE_HUSH_FAST
7241 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007242 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007243 signal(SIGCHLD, SIGCHLD_handler);
7244#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007245 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007246 signal(SIGCHLD, SIG_DFL);
7247#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007248
7249 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007250}
7251
7252#if ENABLE_HUSH_JOB
7253/* helper */
7254static void maybe_set_to_sigexit(int sig)
7255{
7256 void (*handler)(int);
7257 /* non_DFL_mask'ed signals are, well, masked,
7258 * no need to set handler for them.
7259 */
7260 if (!((G.non_DFL_mask >> sig) & 1)) {
7261 handler = signal(sig, sigexit);
7262 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7263 signal(sig, handler);
7264 }
7265}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007266/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007267static void set_fatal_handlers(void)
7268{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007269 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007270 if (HUSH_DEBUG) {
7271 maybe_set_to_sigexit(SIGILL );
7272 maybe_set_to_sigexit(SIGFPE );
7273 maybe_set_to_sigexit(SIGBUS );
7274 maybe_set_to_sigexit(SIGSEGV);
7275 maybe_set_to_sigexit(SIGTRAP);
7276 } /* else: hush is perfect. what SEGV? */
7277 maybe_set_to_sigexit(SIGABRT);
7278 /* bash 3.2 seems to handle these just like 'fatal' ones */
7279 maybe_set_to_sigexit(SIGPIPE);
7280 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007281 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007282 * if we aren't interactive... but in this case
7283 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007284 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007285 /*maybe_set_to_sigexit(SIGTERM);*/
7286 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007287}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007288#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007289
Denis Vlasenkod5762932009-03-31 11:22:57 +00007290static int set_mode(const char cstate, const char mode)
7291{
7292 int state = (cstate == '-' ? 1 : 0);
7293 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007294 case 'n': G.n_mode = state; break;
7295 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007296 default: return EXIT_FAILURE;
7297 }
7298 return EXIT_SUCCESS;
7299}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007300
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007301int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007302int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007303{
7304 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007305 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007306 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007307 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00007308
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007309 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007310 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007311 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007312#if !BB_MMU
7313 G.argv0_for_re_execing = argv[0];
7314#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007315 /* Deal with HUSH_VERSION */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007316 G.shell_ver.flg_export = 1;
7317 G.shell_ver.flg_read_only = 1;
7318 /* Code which handles ${var/P/R} needs writable values for all variables,
7319 * therefore we xstrdup: */
7320 G.shell_ver.varstr = xstrdup(hush_version_str),
Denis Vlasenko87a86552008-07-29 19:43:10 +00007321 G.top_var = &G.shell_ver;
Denys Vlasenko605067b2010-09-06 12:10:51 +02007322 /* Create shell local variables from the values
7323 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007324 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007325 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007326 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007327 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007328 if (e) while (*e) {
7329 char *value = strchr(*e, '=');
7330 if (value) { /* paranoia */
7331 cur_var->next = xzalloc(sizeof(*cur_var));
7332 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007333 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007334 cur_var->max_len = strlen(*e);
7335 cur_var->flg_export = 1;
7336 }
7337 e++;
7338 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007339 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7340 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7341 putenv(G.shell_ver.varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007342
7343 /* Export PWD */
7344 set_pwd_var(/*exp:*/ 1);
7345 /* bash also exports SHLVL and _,
7346 * and sets (but doesn't export) the following variables:
7347 * BASH=/bin/bash
7348 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7349 * BASH_VERSION='3.2.0(1)-release'
7350 * HOSTTYPE=i386
7351 * MACHTYPE=i386-pc-linux-gnu
7352 * OSTYPE=linux-gnu
7353 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007354 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007355 * EUID=<NNNNN>
7356 * UID=<NNNNN>
7357 * GROUPS=()
7358 * LINES=<NNN>
7359 * COLUMNS=<NNN>
7360 * BASH_ARGC=()
7361 * BASH_ARGV=()
7362 * BASH_LINENO=()
7363 * BASH_SOURCE=()
7364 * DIRSTACK=()
7365 * PIPESTATUS=([0]="0")
7366 * HISTFILE=/<xxx>/.bash_history
7367 * HISTFILESIZE=500
7368 * HISTSIZE=500
7369 * MAILCHECK=60
7370 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7371 * SHELL=/bin/bash
7372 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7373 * TERM=dumb
7374 * OPTERR=1
7375 * OPTIND=1
7376 * IFS=$' \t\n'
7377 * PS1='\s-\v\$ '
7378 * PS2='> '
7379 * PS4='+ '
7380 */
7381
Denis Vlasenko38f63192007-01-22 09:03:07 +00007382#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007383 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007384#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007385 G.global_argc = argc;
7386 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007387 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007388 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007389
Denis Vlasenkoed782372009-04-10 00:45:02 +00007390 if (setjmp(die_jmp)) {
7391 /* xfunc has failed! die die die */
7392 /* no EXIT traps, this is an escape hatch! */
7393 G.exiting = 1;
7394 hush_exit(xfunc_error_retval);
7395 }
7396
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007397 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007398 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007399 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007400 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007401 * in order to intercept (more) signals.
7402 */
7403
7404 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007405 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007406 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007407 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007408 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007409#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007410 "<:$:R:V:"
7411# if ENABLE_HUSH_FUNCTIONS
7412 "F:"
7413# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007414#endif
7415 );
7416 if (opt <= 0)
7417 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007418 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007419 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007420 /* Possibilities:
7421 * sh ... -c 'script'
7422 * sh ... -c 'script' ARG0 [ARG1...]
7423 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007424 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007425 * "" needs to be replaced with NULL
7426 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007427 * Note: the form without ARG0 never happens:
7428 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007429 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007430 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007431 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007432 G.root_ppid = getppid();
7433 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007434 G.global_argv = argv + optind;
7435 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007436 if (builtin_argc) {
7437 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7438 const struct built_in_command *x;
7439
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007440 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007441 x = find_builtin(optarg);
7442 if (x) { /* paranoia */
7443 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7444 G.global_argv += builtin_argc;
7445 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007446 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007447 }
7448 goto final_return;
7449 }
7450 if (!G.global_argv[0]) {
7451 /* -c 'script' (no params): prevent empty $0 */
7452 G.global_argv--; /* points to argv[i] of 'script' */
7453 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007454 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007455 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007456 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007457 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007458 goto final_return;
7459 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007460 /* Well, we cannot just declare interactiveness,
7461 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007462 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007463 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007464 case 's':
7465 /* "-s" means "read from stdin", but this is how we always
7466 * operate, so simply do nothing here. */
7467 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007468#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007469 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007470 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007471 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007472 case '$': {
7473 unsigned long long empty_trap_mask;
7474
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007475 G.root_pid = bb_strtou(optarg, &optarg, 16);
7476 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007477 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7478 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007479 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7480 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007481 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007482 optarg++;
7483 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007484 optarg++;
7485 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7486 if (empty_trap_mask != 0) {
7487 int sig;
7488 init_sigmasks();
7489 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7490 for (sig = 1; sig < NSIG; sig++) {
7491 if (empty_trap_mask & (1LL << sig)) {
7492 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7493 sigaddset(&G.blocked_set, sig);
7494 }
7495 }
7496 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7497 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007498# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007499 optarg++;
7500 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007501# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007502 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007503 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007504 case 'R':
7505 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007506 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007507 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007508# if ENABLE_HUSH_FUNCTIONS
7509 case 'F': {
7510 struct function *funcp = new_function(optarg);
7511 /* funcp->name is already set to optarg */
7512 /* funcp->body is set to NULL. It's a special case. */
7513 funcp->body_as_string = argv[optind];
7514 optind++;
7515 break;
7516 }
7517# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007518#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007519 case 'n':
7520 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007521 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007522 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007523 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007524#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007525 fprintf(stderr, "Usage: sh [FILE]...\n"
7526 " or: sh -c command [args]...\n\n");
7527 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007528#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007529 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007530#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007531 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007532 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007533
Denys Vlasenkodea47882009-10-09 15:40:49 +02007534 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007535 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007536 G.root_ppid = getppid();
7537 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007538
7539 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007540 if (argv[0] && argv[0][0] == '-') {
7541 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007542 debug_printf("sourcing /etc/profile\n");
7543 input = fopen_for_read("/etc/profile");
7544 if (input != NULL) {
7545 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007546 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007547 parse_and_run_file(input);
7548 fclose(input);
7549 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007550 /* bash: after sourcing /etc/profile,
7551 * tries to source (in the given order):
7552 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007553 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007554 * bash also sources ~/.bash_logout on exit.
7555 * If called as sh, skips .bash_XXX files.
7556 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007557 }
7558
Denis Vlasenkof9375282009-04-05 19:13:39 +00007559 if (argv[optind]) {
7560 FILE *input;
7561 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007562 * "bash <script>" (which is never interactive (unless -i?))
7563 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007564 * If called as sh, does the same but with $ENV.
7565 */
7566 debug_printf("running script '%s'\n", argv[optind]);
7567 G.global_argv = argv + optind;
7568 G.global_argc = argc - optind;
7569 input = xfopen_for_read(argv[optind]);
7570 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007571 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007572 parse_and_run_file(input);
7573#if ENABLE_FEATURE_CLEAN_UP
7574 fclose(input);
7575#endif
7576 goto final_return;
7577 }
7578
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007579 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007580 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007581 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007582
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007583 /* A shell is interactive if the '-i' flag was given,
7584 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007585 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007586 * no arguments remaining or the -s flag given
7587 * standard input is a terminal
7588 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007589 * Refer to Posix.2, the description of the 'sh' utility.
7590 */
7591#if ENABLE_HUSH_JOB
7592 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007593 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7594 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7595 if (G_saved_tty_pgrp < 0)
7596 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007597
7598 /* try to dup stdin to high fd#, >= 255 */
7599 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7600 if (G_interactive_fd < 0) {
7601 /* try to dup to any fd */
7602 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007603 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007604 /* give up */
7605 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007606 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007607 }
7608 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007609// TODO: track & disallow any attempts of user
7610// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007611 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007612 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007613 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007614 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007615
Mike Frysinger38478a62009-05-20 04:48:06 -04007616 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007617 /* If we were run as 'hush &', sleep until we are
7618 * in the foreground (tty pgrp == our pgrp).
7619 * If we get started under a job aware app (like bash),
7620 * make sure we are now in charge so we don't fight over
7621 * who gets the foreground */
7622 while (1) {
7623 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007624 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7625 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007626 break;
7627 /* send TTIN to ourself (should stop us) */
7628 kill(- shell_pgrp, SIGTTIN);
7629 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007630 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007631
Denis Vlasenkof9375282009-04-05 19:13:39 +00007632 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007633 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007634
Mike Frysinger38478a62009-05-20 04:48:06 -04007635 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007636 /* Set other signals to restore saved_tty_pgrp */
7637 set_fatal_handlers();
7638 /* Put ourselves in our own process group
7639 * (bash, too, does this only if ctty is available) */
7640 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7641 /* Grab control of the terminal */
7642 tcsetpgrp(G_interactive_fd, getpid());
7643 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007644 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007645 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007646 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007647 } else {
7648 init_sigmasks();
7649 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007650#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007651 /* No job control compiled in, only prompt/line editing */
7652 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007653 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7654 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007655 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007656 G_interactive_fd = dup(STDIN_FILENO);
7657 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007658 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007659 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007660 }
7661 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007662 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007663 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007664 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007665 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007666#else
7667 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007668 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007669#endif
7670 /* bash:
7671 * if interactive but not a login shell, sources ~/.bashrc
7672 * (--norc turns this off, --rcfile <file> overrides)
7673 */
7674
7675 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007676 /* note: ash and hush share this string */
7677 printf("\n\n%s %s\n"
7678 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7679 "\n",
7680 bb_banner,
7681 "hush - the humble shell"
7682 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007683 }
7684
Denis Vlasenkof9375282009-04-05 19:13:39 +00007685 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007686
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007687 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007688#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007689 if (G.cwd != bb_msg_unknown)
7690 free((char*)G.cwd);
7691 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007692 while (cur_var) {
7693 struct variable *tmp = cur_var;
7694 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007695 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007696 cur_var = cur_var->next;
7697 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007698 }
Eric Andersen25f27032001-04-26 23:22:31 +00007699#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007700 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007701}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007702
7703
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007704#if ENABLE_MSH
7705int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7706int msh_main(int argc, char **argv)
7707{
7708 //bb_error_msg("msh is deprecated, please use hush instead");
7709 return hush_main(argc, argv);
7710}
7711#endif
7712
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007713
7714/*
7715 * Built-ins
7716 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007717static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007718{
7719 return 0;
7720}
7721
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007722static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007723{
7724 int argc = 0;
7725 while (*argv) {
7726 argc++;
7727 argv++;
7728 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007729 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007730}
7731
7732static int FAST_FUNC builtin_test(char **argv)
7733{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007734 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007735}
7736
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007737static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007738{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007739 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007740}
7741
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007742#if ENABLE_PRINTF
7743static int FAST_FUNC builtin_printf(char **argv)
7744{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007745 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007746}
7747#endif
7748
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007749static char **skip_dash_dash(char **argv)
7750{
7751 argv++;
7752 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7753 argv++;
7754 return argv;
7755}
7756
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007757static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007758{
7759 int rcode = EXIT_SUCCESS;
7760
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007761 argv = skip_dash_dash(argv);
7762 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007763 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007764 /* bash:
7765 * eval "echo Hi; done" ("done" is syntax error):
7766 * "echo Hi" will not execute too.
7767 */
7768 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007769 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007770 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007771 }
7772 return rcode;
7773}
7774
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007775static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007776{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007777 const char *newdir;
7778
7779 argv = skip_dash_dash(argv);
7780 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007781 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007782 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007783 * bash says "bash: cd: HOME not set" and does nothing
7784 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007785 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007786 const char *home = get_local_var_value("HOME");
7787 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007788 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007789 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007790 /* Mimic bash message exactly */
7791 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007792 return EXIT_FAILURE;
7793 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007794 /* Read current dir (get_cwd(1) is inside) and set PWD.
7795 * Note: do not enforce exporting. If PWD was unset or unexported,
7796 * set it again, but do not export. bash does the same.
7797 */
7798 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007799 return EXIT_SUCCESS;
7800}
7801
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007802static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007803{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007804 argv = skip_dash_dash(argv);
7805 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007806 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007807
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007808 /* Careful: we can end up here after [v]fork. Do not restore
7809 * tty pgrp then, only top-level shell process does that */
7810 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7811 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7812
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007813 /* TODO: if exec fails, bash does NOT exit! We do.
7814 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7815 * and tcsetpgrp, and this is inherently racy.
7816 */
7817 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007818}
7819
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007820static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007821{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007822 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007823
7824 /* interactive bash:
7825 * # trap "echo EEE" EXIT
7826 * # exit
7827 * exit
7828 * There are stopped jobs.
7829 * (if there are _stopped_ jobs, running ones don't count)
7830 * # exit
7831 * exit
7832 # EEE (then bash exits)
7833 *
7834 * we can use G.exiting = -1 as indicator "last cmd was exit"
7835 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007836
7837 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007838 argv = skip_dash_dash(argv);
7839 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007840 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007841 /* mimic bash: exit 123abc == exit 255 + error msg */
7842 xfunc_error_retval = 255;
7843 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007844 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007845}
7846
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007847static void print_escaped(const char *s)
7848{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007849 if (*s == '\'')
7850 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007851 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007852 const char *p = strchrnul(s, '\'');
7853 /* print 'xxxx', possibly just '' */
7854 printf("'%.*s'", (int)(p - s), s);
7855 if (*p == '\0')
7856 break;
7857 s = p;
7858 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007859 /* s points to '; print "'''...'''" */
7860 putchar('"');
7861 do putchar('\''); while (*++s == '\'');
7862 putchar('"');
7863 } while (*s);
7864}
7865
Denys Vlasenko295fef82009-06-03 12:47:26 +02007866#if !ENABLE_HUSH_LOCAL
7867#define helper_export_local(argv, exp, lvl) \
7868 helper_export_local(argv, exp)
7869#endif
7870static void helper_export_local(char **argv, int exp, int lvl)
7871{
7872 do {
7873 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007874 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02007875
7876 /* So far we do not check that name is valid (TODO?) */
7877
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007878 if (*name_end == '\0') {
7879 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02007880
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007881 vpp = get_ptr_to_local_var(name, name_end - name);
7882 var = vpp ? *vpp : NULL;
7883
Denys Vlasenko295fef82009-06-03 12:47:26 +02007884 if (exp == -1) { /* unexporting? */
7885 /* export -n NAME (without =VALUE) */
7886 if (var) {
7887 var->flg_export = 0;
7888 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7889 unsetenv(name);
7890 } /* else: export -n NOT_EXISTING_VAR: no-op */
7891 continue;
7892 }
7893 if (exp == 1) { /* exporting? */
7894 /* export NAME (without =VALUE) */
7895 if (var) {
7896 var->flg_export = 1;
7897 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7898 putenv(var->varstr);
7899 continue;
7900 }
7901 }
7902 /* Exporting non-existing variable.
7903 * bash does not put it in environment,
7904 * but remembers that it is exported,
7905 * and does put it in env when it is set later.
7906 * We just set it to "" and export. */
7907 /* Or, it's "local NAME" (without =VALUE).
7908 * bash sets the value to "". */
7909 name = xasprintf("%s=", name);
7910 } else {
7911 /* (Un)exporting/making local NAME=VALUE */
7912 name = xstrdup(name);
7913 }
7914 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7915 } while (*++argv);
7916}
7917
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007918static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007919{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007920 unsigned opt_unexport;
7921
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007922#if ENABLE_HUSH_EXPORT_N
7923 /* "!": do not abort on errors */
7924 opt_unexport = getopt32(argv, "!n");
7925 if (opt_unexport == (uint32_t)-1)
7926 return EXIT_FAILURE;
7927 argv += optind;
7928#else
7929 opt_unexport = 0;
7930 argv++;
7931#endif
7932
7933 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007934 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007935 if (e) {
7936 while (*e) {
7937#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007938 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007939#else
7940 /* ash emits: export VAR='VAL'
7941 * bash: declare -x VAR="VAL"
7942 * we follow ash example */
7943 const char *s = *e++;
7944 const char *p = strchr(s, '=');
7945
7946 if (!p) /* wtf? take next variable */
7947 continue;
7948 /* export var= */
7949 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007950 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007951 putchar('\n');
7952#endif
7953 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007954 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007955 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007956 return EXIT_SUCCESS;
7957 }
7958
Denys Vlasenko295fef82009-06-03 12:47:26 +02007959 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007960
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007961 return EXIT_SUCCESS;
7962}
7963
Denys Vlasenko295fef82009-06-03 12:47:26 +02007964#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007965static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007966{
7967 if (G.func_nest_level == 0) {
7968 bb_error_msg("%s: not in a function", argv[0]);
7969 return EXIT_FAILURE; /* bash compat */
7970 }
7971 helper_export_local(argv, 0, G.func_nest_level);
7972 return EXIT_SUCCESS;
7973}
7974#endif
7975
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007976static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007977{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007978 int sig;
7979 char *new_cmd;
7980
7981 if (!G.traps)
7982 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7983
7984 argv++;
7985 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007986 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007987 /* No args: print all trapped */
7988 for (i = 0; i < NSIG; ++i) {
7989 if (G.traps[i]) {
7990 printf("trap -- ");
7991 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007992 /* note: bash adds "SIG", but only if invoked
7993 * as "bash". If called as "sh", or if set -o posix,
7994 * then it prints short signal names.
7995 * We are printing short names: */
7996 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007997 }
7998 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007999 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008000 return EXIT_SUCCESS;
8001 }
8002
8003 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008004 /* If first arg is a number: reset all specified signals */
8005 sig = bb_strtou(*argv, NULL, 10);
8006 if (errno == 0) {
8007 int ret;
8008 process_sig_list:
8009 ret = EXIT_SUCCESS;
8010 while (*argv) {
8011 sig = get_signum(*argv++);
8012 if (sig < 0 || sig >= NSIG) {
8013 ret = EXIT_FAILURE;
8014 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008015 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008016 continue;
8017 }
8018
8019 free(G.traps[sig]);
8020 G.traps[sig] = xstrdup(new_cmd);
8021
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008022 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008023 get_signame(sig), sig, G.traps[sig]);
8024
8025 /* There is no signal for 0 (EXIT) */
8026 if (sig == 0)
8027 continue;
8028
8029 if (new_cmd) {
8030 sigaddset(&G.blocked_set, sig);
8031 } else {
8032 /* There was a trap handler, we are removing it
8033 * (if sig has non-DFL handling,
8034 * we don't need to do anything) */
8035 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8036 continue;
8037 sigdelset(&G.blocked_set, sig);
8038 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008039 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008040 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008041 return ret;
8042 }
8043
8044 if (!argv[1]) { /* no second arg */
8045 bb_error_msg("trap: invalid arguments");
8046 return EXIT_FAILURE;
8047 }
8048
8049 /* First arg is "-": reset all specified to default */
8050 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8051 /* Everything else: set arg as signal handler
8052 * (includes "" case, which ignores signal) */
8053 if (argv[0][0] == '-') {
8054 if (argv[0][1] == '\0') { /* "-" */
8055 /* new_cmd remains NULL: "reset these sigs" */
8056 goto reset_traps;
8057 }
8058 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8059 argv++;
8060 }
8061 /* else: "-something", no special meaning */
8062 }
8063 new_cmd = *argv;
8064 reset_traps:
8065 argv++;
8066 goto process_sig_list;
8067}
8068
Mike Frysinger93cadc22009-05-27 17:06:25 -04008069/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008070static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008071{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008072 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008073
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008074 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008075 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008076 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008077
8078 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008079 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008080 type = "an alias";*/
8081#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008082 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008083 type = "a function";
8084#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008085 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008086 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008087 else if ((path = find_in_path(*argv)) != NULL)
8088 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008089 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008090 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008091 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008092 continue;
8093 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008094
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008095 printf("%s is %s\n", *argv, type);
8096 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008097 }
8098
8099 return ret;
8100}
8101
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008102#if ENABLE_HUSH_JOB
8103/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008104static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008105{
8106 int i, jobnum;
8107 struct pipe *pi;
8108
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008109 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008110 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008111
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008112 /* If they gave us no args, assume they want the last backgrounded task */
8113 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008114 for (pi = G.job_list; pi; pi = pi->next) {
8115 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008116 goto found;
8117 }
8118 }
8119 bb_error_msg("%s: no current job", argv[0]);
8120 return EXIT_FAILURE;
8121 }
8122 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8123 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8124 return EXIT_FAILURE;
8125 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008126 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008127 if (pi->jobid == jobnum) {
8128 goto found;
8129 }
8130 }
8131 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8132 return EXIT_FAILURE;
8133 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008134 /* TODO: bash prints a string representation
8135 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008136 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008137 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008138 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008139 }
8140
8141 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008142 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8143 for (i = 0; i < pi->num_cmds; i++) {
8144 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8145 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008146 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008147 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008148
8149 i = kill(- pi->pgrp, SIGCONT);
8150 if (i < 0) {
8151 if (errno == ESRCH) {
8152 delete_finished_bg_job(pi);
8153 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008154 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008155 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008156 }
8157
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008158 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008159 remove_bg_job(pi);
8160 return checkjobs_and_fg_shell(pi);
8161 }
8162 return EXIT_SUCCESS;
8163}
8164#endif
8165
8166#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008167static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008168{
8169 const struct built_in_command *x;
8170
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008171 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008172 "Built-in commands:\n"
8173 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008174 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008175 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008176 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008177 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008178 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008179 return EXIT_SUCCESS;
8180}
8181#endif
8182
8183#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008184static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008185{
8186 struct pipe *job;
8187 const char *status_string;
8188
Denis Vlasenko87a86552008-07-29 19:43:10 +00008189 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008190 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008191 status_string = "Stopped";
8192 else
8193 status_string = "Running";
8194
8195 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8196 }
8197 return EXIT_SUCCESS;
8198}
8199#endif
8200
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008201#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008202static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008203{
8204 void *p;
8205 unsigned long l;
8206
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008207# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008208 /* Optional. Reduces probability of false positives */
8209 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008210# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008211 /* Crude attempt to find where "free memory" starts,
8212 * sans fragmentation. */
8213 p = malloc(240);
8214 l = (unsigned long)p;
8215 free(p);
8216 p = malloc(3400);
8217 if (l < (unsigned long)p) l = (unsigned long)p;
8218 free(p);
8219
8220 if (!G.memleak_value)
8221 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008222
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008223 l -= G.memleak_value;
8224 if ((long)l < 0)
8225 l = 0;
8226 l /= 1024;
8227 if (l > 127)
8228 l = 127;
8229
8230 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8231 return l;
8232}
8233#endif
8234
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008235static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008236{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008237 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008238 return EXIT_SUCCESS;
8239}
8240
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008241static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008242{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008243 const char *r;
8244 char *opt_n = NULL;
8245 char *opt_p = NULL;
8246 char *opt_t = NULL;
8247 char *opt_u = NULL;
8248 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008249
Denys Vlasenko03dad222010-01-12 23:29:57 +01008250 /* "!": do not abort on errors.
8251 * Option string must start with "sr" to match BUILTIN_READ_xxx
8252 */
8253 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8254 if (read_flags == (uint32_t)-1)
8255 return EXIT_FAILURE;
8256 argv += optind;
8257
8258 r = shell_builtin_read(set_local_var_from_halves,
8259 argv,
8260 get_local_var_value("IFS"), /* can be NULL */
8261 read_flags,
8262 opt_n,
8263 opt_p,
8264 opt_t,
8265 opt_u
8266 );
8267
8268 if ((uintptr_t)r > 1) {
8269 bb_error_msg("%s", r);
8270 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008271 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008272
Denys Vlasenko03dad222010-01-12 23:29:57 +01008273 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008274}
8275
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008276/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8277 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008278 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008279 * set [-abCefhmnuvx] [-o option] [argument...]
8280 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008281 * set -- [argument...]
8282 * set -o
8283 * set +o
8284 * Implementations shall support the options in both their hyphen and
8285 * plus-sign forms. These options can also be specified as options to sh.
8286 * Examples:
8287 * Write out all variables and their values: set
8288 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8289 * Turn on the -x and -v options: set -xv
8290 * Unset all positional parameters: set --
8291 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8292 * Set the positional parameters to the expansion of x, even if x expands
8293 * with a leading '-' or '+': set -- $x
8294 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008295 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008296 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008297static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008298{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008299 int n;
8300 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008301 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008302
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008303 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008304 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008305 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008306 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008307 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008308 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008309
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008310 do {
8311 if (!strcmp(arg, "--")) {
8312 ++argv;
8313 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008314 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008315 if (arg[0] != '+' && arg[0] != '-')
8316 break;
8317 for (n = 1; arg[n]; ++n)
8318 if (set_mode(arg[0], arg[n]))
8319 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008320 } while ((arg = *++argv) != NULL);
8321 /* Now argv[0] is 1st argument */
8322
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008323 if (arg == NULL)
8324 return EXIT_SUCCESS;
8325 set_argv:
8326
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008327 /* NB: G.global_argv[0] ($0) is never freed/changed */
8328 g_argv = G.global_argv;
8329 if (G.global_args_malloced) {
8330 pp = g_argv;
8331 while (*++pp)
8332 free(*pp);
8333 g_argv[1] = NULL;
8334 } else {
8335 G.global_args_malloced = 1;
8336 pp = xzalloc(sizeof(pp[0]) * 2);
8337 pp[0] = g_argv[0]; /* retain $0 */
8338 g_argv = pp;
8339 }
8340 /* This realloc's G.global_argv */
8341 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8342
8343 n = 1;
8344 while (*++pp)
8345 n++;
8346 G.global_argc = n;
8347
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008348 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008349
8350 /* Nothing known, so abort */
8351 error:
8352 bb_error_msg("set: %s: invalid option", arg);
8353 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008354}
8355
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008356static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008357{
8358 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008359 argv = skip_dash_dash(argv);
8360 if (argv[0]) {
8361 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008362 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008363 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008364 if (G.global_args_malloced) {
8365 int m = 1;
8366 while (m <= n)
8367 free(G.global_argv[m++]);
8368 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008369 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008370 memmove(&G.global_argv[1], &G.global_argv[n+1],
8371 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008372 return EXIT_SUCCESS;
8373 }
8374 return EXIT_FAILURE;
8375}
8376
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008377static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008378{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008379 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008380 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008381 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008382#if ENABLE_HUSH_FUNCTIONS
8383 smallint sv_flg;
8384#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008385
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008386 argv = skip_dash_dash(argv);
8387 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008388 if (!filename) {
8389 /* bash says: "bash: .: filename argument required" */
8390 return 2; /* bash compat */
8391 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008392 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008393 if (!strchr(filename, '/')) {
8394 arg_path = find_in_path(filename);
8395 if (arg_path)
8396 filename = arg_path;
8397 }
8398 input = fopen_or_warn(filename, "r");
8399 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008400 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008401 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008402 return EXIT_FAILURE;
8403 }
8404 close_on_exec_on(fileno(input));
8405
Mike Frysinger885b6f22009-04-18 21:04:25 +00008406#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008407 sv_flg = G.flag_return_in_progress;
8408 /* "we are inside sourced file, ok to use return" */
8409 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008410#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008411 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008412
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008413 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008414 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008415
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008416 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008417#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008418 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008419#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008420
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008421 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008422}
8423
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008424static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008425{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008426 int rc;
8427 mode_t mask;
8428
8429 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008430 argv = skip_dash_dash(argv);
8431 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008432 mode_t old_mask = mask;
8433
8434 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008435 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008436 mask ^= 0777;
8437 if (rc == 0) {
8438 mask = old_mask;
8439 /* bash messages:
8440 * bash: umask: 'q': invalid symbolic mode operator
8441 * bash: umask: 999: octal number out of range
8442 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008443 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008444 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008445 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008446 rc = 1;
8447 /* Mimic bash */
8448 printf("%04o\n", (unsigned) mask);
8449 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008450 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008451 umask(mask);
8452
8453 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008454}
8455
Mike Frysingerd690f682009-03-30 06:50:54 +00008456/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008457static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008458{
Mike Frysingerd690f682009-03-30 06:50:54 +00008459 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008460 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008461
Denis Vlasenko28e67962009-04-26 23:22:40 +00008462 /* "!": do not abort on errors */
8463 /* "+": stop at 1st non-option */
8464 opts = getopt32(argv, "!+vf");
8465 if (opts == (unsigned)-1)
8466 return EXIT_FAILURE;
8467 if (opts == 3) {
8468 bb_error_msg("unset: -v and -f are exclusive");
8469 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008470 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008471 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008472
8473 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008474 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008475 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008476 if (unset_local_var(*argv)) {
8477 /* unset <nonexistent_var> doesn't fail.
8478 * Error is when one tries to unset RO var.
8479 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008480 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008481 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008482 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008483#if ENABLE_HUSH_FUNCTIONS
8484 else {
8485 unset_func(*argv);
8486 }
8487#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008488 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008489 }
8490 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008491}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008492
Mike Frysinger56bdea12009-03-28 20:01:58 +00008493/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008494static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008495{
8496 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008497 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008498
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008499 argv = skip_dash_dash(argv);
8500 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008501 /* Don't care about wait results */
8502 /* Note 1: must wait until there are no more children */
8503 /* Note 2: must be interruptible */
8504 /* Examples:
8505 * $ sleep 3 & sleep 6 & wait
8506 * [1] 30934 sleep 3
8507 * [2] 30935 sleep 6
8508 * [1] Done sleep 3
8509 * [2] Done sleep 6
8510 * $ sleep 3 & sleep 6 & wait
8511 * [1] 30936 sleep 3
8512 * [2] 30937 sleep 6
8513 * [1] Done sleep 3
8514 * ^C <-- after ~4 sec from keyboard
8515 * $
8516 */
8517 sigaddset(&G.blocked_set, SIGCHLD);
8518 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8519 while (1) {
8520 checkjobs(NULL);
8521 if (errno == ECHILD)
8522 break;
8523 /* Wait for SIGCHLD or any other signal of interest */
8524 /* sigtimedwait with infinite timeout: */
8525 sig = sigwaitinfo(&G.blocked_set, NULL);
8526 if (sig > 0) {
8527 sig = check_and_run_traps(sig);
8528 if (sig && sig != SIGCHLD) { /* see note 2 */
8529 ret = 128 + sig;
8530 break;
8531 }
8532 }
8533 }
8534 sigdelset(&G.blocked_set, SIGCHLD);
8535 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8536 return ret;
8537 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008538
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008539 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008540 while (*argv) {
8541 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008542 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008543 /* mimic bash message */
8544 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008545 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008546 }
8547 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008548 if (WIFSIGNALED(status))
8549 ret = 128 + WTERMSIG(status);
8550 else if (WIFEXITED(status))
8551 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008552 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008553 ret = EXIT_FAILURE;
8554 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008555 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008556 ret = 127;
8557 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008558 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008559 }
8560
8561 return ret;
8562}
8563
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008564#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8565static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8566{
8567 if (argv[1]) {
8568 def = bb_strtou(argv[1], NULL, 10);
8569 if (errno || def < def_min || argv[2]) {
8570 bb_error_msg("%s: bad arguments", argv[0]);
8571 def = UINT_MAX;
8572 }
8573 }
8574 return def;
8575}
8576#endif
8577
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008578#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008579static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008580{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008581 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008582 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008583 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008584 return EXIT_SUCCESS; /* bash compat */
8585 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008586 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008587
8588 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8589 if (depth == UINT_MAX)
8590 G.flag_break_continue = BC_BREAK;
8591 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008592 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008593
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008594 return EXIT_SUCCESS;
8595}
8596
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008597static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008598{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008599 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8600 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008601}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008602#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008603
8604#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008605static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008606{
8607 int rc;
8608
8609 if (G.flag_return_in_progress != -1) {
8610 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8611 return EXIT_FAILURE; /* bash compat */
8612 }
8613
8614 G.flag_return_in_progress = 1;
8615
8616 /* bash:
8617 * out of range: wraps around at 256, does not error out
8618 * non-numeric param:
8619 * f() { false; return qwe; }; f; echo $?
8620 * bash: return: qwe: numeric argument required <== we do this
8621 * 255 <== we also do this
8622 */
8623 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8624 return rc;
8625}
8626#endif