blob: 752efd0c8b985d0b1872a49bc26317471a20c479 [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:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200149//config:config HUSH_SAVEHISTORY
150//config: bool "Save command history to .hush_history"
151//config: default y
152//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
153//config: help
154//config: Enable history saving in hush.
155//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200156//config:config HUSH_JOB
157//config: bool "Job control"
158//config: default y
159//config: depends on HUSH_INTERACTIVE
160//config: help
161//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
162//config: command (not entire shell), fg/bg builtins work. Without this option,
163//config: "cmd &" still works by simply spawning a process and immediately
164//config: prompting for next command (or executing next command in a script),
165//config: but no separate process group is formed.
166//config:
167//config:config HUSH_TICK
168//config: bool "Process substitution"
169//config: default y
170//config: depends on HUSH
171//config: help
172//config: Enable process substitution `command` and $(command) in hush.
173//config:
174//config:config HUSH_IF
175//config: bool "Support if/then/elif/else/fi"
176//config: default y
177//config: depends on HUSH
178//config: help
179//config: Enable if/then/elif/else/fi in hush.
180//config:
181//config:config HUSH_LOOPS
182//config: bool "Support for, while and until loops"
183//config: default y
184//config: depends on HUSH
185//config: help
186//config: Enable for, while and until loops in hush.
187//config:
188//config:config HUSH_CASE
189//config: bool "Support case ... esac statement"
190//config: default y
191//config: depends on HUSH
192//config: help
193//config: Enable case ... esac statement in hush. +400 bytes.
194//config:
195//config:config HUSH_FUNCTIONS
196//config: bool "Support funcname() { commands; } syntax"
197//config: default y
198//config: depends on HUSH
199//config: help
200//config: Enable support for shell functions in hush. +800 bytes.
201//config:
202//config:config HUSH_LOCAL
203//config: bool "Support local builtin"
204//config: default y
205//config: depends on HUSH_FUNCTIONS
206//config: help
207//config: Enable support for local variables in functions.
208//config:
209//config:config HUSH_RANDOM_SUPPORT
210//config: bool "Pseudorandom generator and $RANDOM variable"
211//config: default y
212//config: depends on HUSH
213//config: help
214//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
215//config: Each read of "$RANDOM" will generate a new pseudorandom value.
216//config:
217//config:config HUSH_EXPORT_N
218//config: bool "Support 'export -n' option"
219//config: default y
220//config: depends on HUSH
221//config: help
222//config: export -n unexports variables. It is a bash extension.
223//config:
224//config:config HUSH_MODE_X
225//config: bool "Support 'hush -x' option and 'set -x' command"
226//config: default y
227//config: depends on HUSH
228//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200229//config: This instructs hush to print commands before execution.
230//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200231//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200232//config:config MSH
233//config: bool "msh (deprecated: aliased to hush)"
234//config: default n
235//config: select HUSH
236//config: help
237//config: msh is deprecated and will be removed, please migrate to hush.
238//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200239
240//usage:#define hush_trivial_usage NOUSAGE_STR
241//usage:#define hush_full_usage ""
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200242//usage:#define msh_trivial_usage NOUSAGE_STR
243//usage:#define msh_full_usage ""
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +0200244//usage:#define sh_trivial_usage NOUSAGE_STR
245//usage:#define sh_full_usage ""
246//usage:#define bash_trivial_usage NOUSAGE_STR
247//usage:#define bash_full_usage ""
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200248
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000249
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200250/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000251#define LEAK_HUNTING 0
252#define BUILD_AS_NOMMU 0
253/* Enable/disable sanity checks. Ok to enable in production,
254 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
255 * Keeping 1 for now even in released versions.
256 */
257#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200258/* Slightly bigger (+200 bytes), but faster hush.
259 * So far it only enables a trick with counting SIGCHLDs and forks,
260 * which allows us to do fewer waitpid's.
261 * (we can detect a case where neither forks were done nor SIGCHLDs happened
262 * and therefore waitpid will return the same result as last time)
263 */
264#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200265/* TODO: implement simplified code for users which do not need ${var%...} ops
266 * So far ${var%...} ops are always enabled:
267 */
268#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000269
270
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000271#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000272# undef BB_MMU
273# undef USE_FOR_NOMMU
274# undef USE_FOR_MMU
275# define BB_MMU 0
276# define USE_FOR_NOMMU(...) __VA_ARGS__
277# define USE_FOR_MMU(...)
278#endif
279
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200280#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100281#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000282/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000283# undef CONFIG_FEATURE_SH_STANDALONE
284# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000285# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100286# undef IF_NOT_FEATURE_SH_STANDALONE
287# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000288# define IF_FEATURE_SH_STANDALONE(...)
289# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000290#endif
291
Denis Vlasenko05743d72008-02-10 12:10:08 +0000292#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000293# undef ENABLE_FEATURE_EDITING
294# define ENABLE_FEATURE_EDITING 0
295# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
296# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000297#endif
298
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000299/* Do we support ANY keywords? */
300#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000301# define HAS_KEYWORDS 1
302# define IF_HAS_KEYWORDS(...) __VA_ARGS__
303# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000304#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000305# define HAS_KEYWORDS 0
306# define IF_HAS_KEYWORDS(...)
307# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000308#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000309
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000310/* If you comment out one of these below, it will be #defined later
311 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000312#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000313/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000314#define debug_printf_parse(...) do {} while (0)
315#define debug_print_tree(a, b) do {} while (0)
316#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000317#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000318#define debug_printf_jobs(...) do {} while (0)
319#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200320#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000321#define debug_printf_glob(...) do {} while (0)
322#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000323#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000324#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000325
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000326#define ERR_PTR ((void*)(long)1)
327
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200328#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000329
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200330#define _SPECIAL_VARS_STR "_*@$!?#"
331#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
332#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200333#if ENABLE_HUSH_BASH_COMPAT
334/* Support / and // replace ops */
335/* Note that // is stored as \ in "encoded" string representation */
336# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
337# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
338# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
339#else
340# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
341# define VAR_SUBST_OPS "%#:-=+?"
342# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
343#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200344
345#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000346
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200347struct variable;
348
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000349static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
350
351/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000352 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000353 */
354#if !BB_MMU
355typedef struct nommu_save_t {
356 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200357 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000358 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000359 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000360} nommu_save_t;
361#endif
362
Denys Vlasenko9b782552010-09-08 13:33:26 +0200363enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000364 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000365#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000366 RES_IF ,
367 RES_THEN ,
368 RES_ELIF ,
369 RES_ELSE ,
370 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000371#endif
372#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000373 RES_FOR ,
374 RES_WHILE ,
375 RES_UNTIL ,
376 RES_DO ,
377 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000378#endif
379#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000380 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000381#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000382#if ENABLE_HUSH_CASE
383 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200384 /* three pseudo-keywords support contrived "case" syntax: */
385 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
386 RES_MATCH , /* "word)" */
387 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000388 RES_ESAC ,
389#endif
390 RES_XXXX ,
391 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200392};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000393
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200394enum {
395 EXP_FLAG_GLOB = 0x200,
396 EXP_FLAG_ESC_GLOB_CHARS = 0x100,
397 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
398};
399
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000400typedef struct o_string {
401 char *data;
402 int length; /* position where data is appended */
403 int maxlen;
404 /* Protect newly added chars against globbing
405 * (by prepending \ to *, ?, [, \) */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200406 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000407 /* At least some part of the string was inside '' or "",
408 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200409 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000410 smallint has_empty_slot;
411 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
412} o_string;
413enum {
414 MAYBE_ASSIGNMENT = 0,
415 DEFINITELY_ASSIGNMENT = 1,
416 NOT_ASSIGNMENT = 2,
417 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
418};
419/* Used for initialization: o_string foo = NULL_O_STRING; */
420#define NULL_O_STRING { NULL }
421
422/* I can almost use ordinary FILE*. Is open_memstream() universally
423 * available? Where is it documented? */
424typedef struct in_str {
425 const char *p;
426 /* eof_flag=1: last char in ->p is really an EOF */
427 char eof_flag; /* meaningless if ->p == NULL */
428 char peek_buf[2];
429#if ENABLE_HUSH_INTERACTIVE
430 smallint promptme;
431 smallint promptmode; /* 0: PS1, 1: PS2 */
432#endif
433 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200434 int (*get) (struct in_str *) FAST_FUNC;
435 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000436} in_str;
437#define i_getch(input) ((input)->get(input))
438#define i_peek(input) ((input)->peek(input))
439
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200440/* The descrip member of this structure is only used to make
441 * debugging output pretty */
442static const struct {
443 int mode;
444 signed char default_fd;
445 char descrip[3];
446} redir_table[] = {
447 { O_RDONLY, 0, "<" },
448 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
449 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
450 { O_CREAT|O_RDWR, 1, "<>" },
451 { O_RDONLY, 0, "<<" },
452/* Should not be needed. Bogus default_fd helps in debugging */
453/* { O_RDONLY, 77, "<<" }, */
454};
455
Eric Andersen25f27032001-04-26 23:22:31 +0000456struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000457 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000458 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000459 int rd_fd; /* fd to redirect */
460 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
461 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000462 smallint rd_type; /* (enum redir_type) */
463 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000464 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200465 * bit 0: do we need to trim leading tabs?
466 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000467 */
Eric Andersen25f27032001-04-26 23:22:31 +0000468};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000469typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200470 REDIRECT_INPUT = 0,
471 REDIRECT_OVERWRITE = 1,
472 REDIRECT_APPEND = 2,
473 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000474 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200475 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000476
477 REDIRFD_CLOSE = -3,
478 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000479 REDIRFD_TO_FILE = -1,
480 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000481
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000482 HEREDOC_SKIPTABS = 1,
483 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000484} redir_type;
485
Eric Andersen25f27032001-04-26 23:22:31 +0000486
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000487struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000488 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000489 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000490 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200491 smallint cmd_type; /* CMD_xxx */
492#define CMD_NORMAL 0
493#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200494#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200495/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200496# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000497#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200498#if ENABLE_HUSH_FUNCTIONS
499# define CMD_FUNCDEF 3
500#endif
501
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200502 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
503 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000504#if !BB_MMU
505 char *group_as_string;
506#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000507#if ENABLE_HUSH_FUNCTIONS
508 struct function *child_func;
509/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200510 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000511 * When we execute "f1() {a;}" cmd, we create new function and clear
512 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200513 * When we execute "f1() {b;}", we notice that f1 exists,
514 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000515 * we put those fields back into cmd->xxx
516 * (struct function has ->parent_cmd ptr to facilitate that).
517 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
518 * Without this trick, loop would execute a;b;b;b;...
519 * instead of correct sequence a;b;a;b;...
520 * When command is freed, it severs the link
521 * (sets ->child_func->parent_cmd to NULL).
522 */
523#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000524 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000525/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
526 * and on execution these are substituted with their values.
527 * Substitution can make _several_ words out of one argv[n]!
528 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000529 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000530 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000531 struct redir_struct *redirects; /* I/O redirections */
532};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000533/* Is there anything in this command at all? */
534#define IS_NULL_CMD(cmd) \
535 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
536
Eric Andersen25f27032001-04-26 23:22:31 +0000537
538struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000539 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000540 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000541 int alive_cmds; /* number of commands running (not exited) */
542 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000543#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000544 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000545 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000546 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000547#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000548 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000549 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000550 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
551 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000552};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000553typedef enum pipe_style {
554 PIPE_SEQ = 1,
555 PIPE_AND = 2,
556 PIPE_OR = 3,
557 PIPE_BG = 4,
558} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000559/* Is there anything in this pipe at all? */
560#define IS_NULL_PIPE(pi) \
561 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000562
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000563/* This holds pointers to the various results of parsing */
564struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000565 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000566 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000567 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000568 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000569 /* last command in pipe (being constructed right now) */
570 struct command *command;
571 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000572 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000573#if !BB_MMU
574 o_string as_string;
575#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000576#if HAS_KEYWORDS
577 smallint ctx_res_w;
578 smallint ctx_inverted; /* "! cmd | cmd" */
579#if ENABLE_HUSH_CASE
580 smallint ctx_dsemicolon; /* ";;" seen */
581#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000582 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
583 int old_flag;
584 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000585 * example: "if pipe1; pipe2; then pipe3; fi"
586 * when we see "if" or "then", we malloc and copy current context,
587 * and make ->stack point to it. then we parse pipeN.
588 * when closing "then" / fi" / whatever is found,
589 * we move list_head into ->stack->command->group,
590 * copy ->stack into current context, and delete ->stack.
591 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000592 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000593 struct parse_context *stack;
594#endif
595};
596
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000597/* On program start, environ points to initial environment.
598 * putenv adds new pointers into it, unsetenv removes them.
599 * Neither of these (de)allocates the strings.
600 * setenv allocates new strings in malloc space and does putenv,
601 * and thus setenv is unusable (leaky) for shell's purposes */
602#define setenv(...) setenv_is_leaky_dont_use()
603struct variable {
604 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000605 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200606#if ENABLE_HUSH_LOCAL
607 unsigned func_nest_level;
608#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000609 int max_len; /* if > 0, name is part of initial env; else name is malloced */
610 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000611 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000612};
613
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000614enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000615 BC_BREAK = 1,
616 BC_CONTINUE = 2,
617};
618
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000619#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000620struct function {
621 struct function *next;
622 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000623 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000624 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200625# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000626 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200627# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000628};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000629#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000630
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000631
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000632/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000633/* Sorted roughly by size (smaller offsets == smaller code) */
634struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000635 /* interactive_fd != 0 means we are an interactive shell.
636 * If we are, then saved_tty_pgrp can also be != 0, meaning
637 * that controlling tty is available. With saved_tty_pgrp == 0,
638 * job control still works, but terminal signals
639 * (^C, ^Z, ^Y, ^\) won't work at all, and background
640 * process groups can only be created with "cmd &".
641 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
642 * to give tty to the foreground process group,
643 * and will take it back when the group is stopped (^Z)
644 * or killed (^C).
645 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000646#if ENABLE_HUSH_INTERACTIVE
647 /* 'interactive_fd' is a fd# open to ctty, if we have one
648 * _AND_ if we decided to act interactively */
649 int interactive_fd;
650 const char *PS1;
651 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000652# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000653#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000654# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000655#endif
656#if ENABLE_FEATURE_EDITING
657 line_input_t *line_input_state;
658#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000659 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200660 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000661 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200662#if ENABLE_HUSH_RANDOM_SUPPORT
663 random_t random_gen;
664#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000665#if ENABLE_HUSH_JOB
666 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000667 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000668 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000669 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400670# define G_saved_tty_pgrp (G.saved_tty_pgrp)
671#else
672# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000673#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000674 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000675#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000676 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000677#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000678#if ENABLE_HUSH_FUNCTIONS
679 /* 0: outside of a function (or sourced file)
680 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000681 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000682 */
683 smallint flag_return_in_progress;
684#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200685 smallint n_mode;
686#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200687 smallint x_mode;
Denys Vlasenko29082232010-07-16 13:52:32 +0200688# define G_x_mode (G.x_mode)
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200689#else
690# define G_x_mode 0
691#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000692 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000693 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000694 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000695 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000696 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100697 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000698 /* how many non-NULL argv's we have. NB: $# + 1 */
699 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000700 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000701#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000702 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000703#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000704#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000705 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000706 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000707#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000708 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000709 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000710 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000711 struct variable shell_ver;
Denys Vlasenko29082232010-07-16 13:52:32 +0200712 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000713#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000714 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200715# if ENABLE_HUSH_LOCAL
716 struct variable **shadowed_vars_pp;
717 unsigned func_nest_level;
718# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000719#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000720 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200721#if ENABLE_HUSH_FAST
722 unsigned count_SIGCHLD;
723 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200724 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200725#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000726 /* which signals have non-DFL handler (even with no traps set)? */
727 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000728 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000729 sigset_t blocked_set;
730 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000731#if HUSH_DEBUG
732 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000733 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000734#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200735 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000736};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000737#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000738/* Not #defining name to G.name - this quickly gets unwieldy
739 * (too many defines). Also, I actually prefer to see when a variable
740 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000741#define INIT_G() do { \
742 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
743} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000744
745
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000746/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200747static int builtin_cd(char **argv) FAST_FUNC;
748static int builtin_echo(char **argv) FAST_FUNC;
749static int builtin_eval(char **argv) FAST_FUNC;
750static int builtin_exec(char **argv) FAST_FUNC;
751static int builtin_exit(char **argv) FAST_FUNC;
752static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000753#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200754static int builtin_fg_bg(char **argv) FAST_FUNC;
755static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000756#endif
757#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200758static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000759#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200760#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200761static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200762#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000763#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200764static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000765#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400766#if ENABLE_PRINTF
767static int builtin_printf(char **argv) FAST_FUNC;
768#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200769static int builtin_pwd(char **argv) FAST_FUNC;
770static int builtin_read(char **argv) FAST_FUNC;
771static int builtin_set(char **argv) FAST_FUNC;
772static int builtin_shift(char **argv) FAST_FUNC;
773static int builtin_source(char **argv) FAST_FUNC;
774static int builtin_test(char **argv) FAST_FUNC;
775static int builtin_trap(char **argv) FAST_FUNC;
776static int builtin_type(char **argv) FAST_FUNC;
777static int builtin_true(char **argv) FAST_FUNC;
778static int builtin_umask(char **argv) FAST_FUNC;
779static int builtin_unset(char **argv) FAST_FUNC;
780static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000781#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200782static int builtin_break(char **argv) FAST_FUNC;
783static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000784#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000785#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200786static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000787#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000788
789/* Table of built-in functions. They can be forked or not, depending on
790 * context: within pipes, they fork. As simple commands, they do not.
791 * When used in non-forking context, they can change global variables
792 * in the parent shell process. If forked, of course they cannot.
793 * For example, 'unset foo | whatever' will parse and run, but foo will
794 * still be set at the end. */
795struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100796 const char *b_cmd;
797 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000798#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100799 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200800# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000801#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200802# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000803#endif
804};
805
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200806static const struct built_in_command bltins1[] = {
807 BLTIN("." , builtin_source , "Run commands in a file"),
808 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000809#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200810 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000811#endif
812#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200813 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000814#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200815 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000816#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200817 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000818#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200819 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
820 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
821 BLTIN("exit" , builtin_exit , "Exit"),
822 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000823#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200824 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000825#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000826#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200827 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000828#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000829#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200830 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000831#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200832#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200833 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200834#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000835#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200836 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000837#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200838 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000839#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200840 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000841#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200842 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
843 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200844#if ENABLE_HUSH_BASH_COMPAT
845 BLTIN("source" , builtin_source , "Run commands in a file"),
846#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200847 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100848 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100849 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200850 BLTIN("umask" , builtin_umask , "Set file creation mask"),
851 BLTIN("unset" , builtin_unset , "Unset variables"),
852 BLTIN("wait" , builtin_wait , "Wait for process"),
853};
854/* For now, echo and test are unconditionally enabled.
855 * Maybe make it configurable? */
856static const struct built_in_command bltins2[] = {
857 BLTIN("[" , builtin_test , NULL),
858 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400859#if ENABLE_PRINTF
860 BLTIN("printf" , builtin_printf , NULL),
861#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200862 BLTIN("pwd" , builtin_pwd , NULL),
863 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000864};
865
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000866
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000867/* Debug printouts.
868 */
869#if HUSH_DEBUG
870/* prevent disasters with G.debug_indent < 0 */
871# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
872# define debug_enter() (G.debug_indent++)
873# define debug_leave() (G.debug_indent--)
874#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200875# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000876# define debug_enter() ((void)0)
877# define debug_leave() ((void)0)
878#endif
879
880#ifndef debug_printf
881# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
882#endif
883
884#ifndef debug_printf_parse
885# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
886#endif
887
888#ifndef debug_printf_exec
889#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
890#endif
891
892#ifndef debug_printf_env
893# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
894#endif
895
896#ifndef debug_printf_jobs
897# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
898# define DEBUG_JOBS 1
899#else
900# define DEBUG_JOBS 0
901#endif
902
903#ifndef debug_printf_expand
904# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
905# define DEBUG_EXPAND 1
906#else
907# define DEBUG_EXPAND 0
908#endif
909
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200910#ifndef debug_printf_varexp
911# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
912#endif
913
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000914#ifndef debug_printf_glob
915# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
916# define DEBUG_GLOB 1
917#else
918# define DEBUG_GLOB 0
919#endif
920
921#ifndef debug_printf_list
922# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
923#endif
924
925#ifndef debug_printf_subst
926# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
927#endif
928
929#ifndef debug_printf_clean
930# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
931# define DEBUG_CLEAN 1
932#else
933# define DEBUG_CLEAN 0
934#endif
935
936#if DEBUG_EXPAND
937static void debug_print_strings(const char *prefix, char **vv)
938{
939 indent();
940 fprintf(stderr, "%s:\n", prefix);
941 while (*vv)
942 fprintf(stderr, " '%s'\n", *vv++);
943}
944#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200945# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000946#endif
947
948
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000949/* Leak hunting. Use hush_leaktool.sh for post-processing.
950 */
951#if LEAK_HUNTING
952static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000953{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000954 void *ptr = xmalloc((size + 0xff) & ~0xff);
955 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
956 return ptr;
957}
958static void *xxrealloc(int lineno, void *ptr, size_t size)
959{
960 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
961 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
962 return ptr;
963}
964static char *xxstrdup(int lineno, const char *str)
965{
966 char *ptr = xstrdup(str);
967 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
968 return ptr;
969}
970static void xxfree(void *ptr)
971{
972 fdprintf(2, "free %p\n", ptr);
973 free(ptr);
974}
Denys Vlasenko8391c482010-05-22 17:50:43 +0200975# define xmalloc(s) xxmalloc(__LINE__, s)
976# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
977# define xstrdup(s) xxstrdup(__LINE__, s)
978# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000979#endif
980
981
982/* Syntax and runtime errors. They always abort scripts.
983 * In interactive use they usually discard unparsed and/or unexecuted commands
984 * and return to the prompt.
985 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
986 */
987#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200988# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000989# define syntax_error(lineno, msg) syntax_error(msg)
990# define syntax_error_at(lineno, msg) syntax_error_at(msg)
991# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
992# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
993# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000994#endif
995
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000996static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000997{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000998 va_list p;
999
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001000#if HUSH_DEBUG >= 2
1001 bb_error_msg("hush.c:%u", lineno);
1002#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001003 va_start(p, fmt);
1004 bb_verror_msg(fmt, p, NULL);
1005 va_end(p);
1006 if (!G_interactive_fd)
1007 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001008}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001009
1010static void syntax_error(unsigned lineno, const char *msg)
1011{
1012 if (msg)
1013 die_if_script(lineno, "syntax error: %s", msg);
1014 else
1015 die_if_script(lineno, "syntax error", NULL);
1016}
1017
1018static void syntax_error_at(unsigned lineno, const char *msg)
1019{
1020 die_if_script(lineno, "syntax error at '%s'", msg);
1021}
1022
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001023static void syntax_error_unterm_str(unsigned lineno, const char *s)
1024{
1025 die_if_script(lineno, "syntax error: unterminated %s", s);
1026}
1027
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001028/* It so happens that all such cases are totally fatal
1029 * even if shell is interactive: EOF while looking for closing
1030 * delimiter. There is nowhere to read stuff from after that,
1031 * it's EOF! The only choice is to terminate.
1032 */
1033static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001034static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001035{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001036 char msg[2] = { ch, '\0' };
1037 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001038 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001039}
1040
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001041static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001042{
1043 char msg[2];
1044 msg[0] = ch;
1045 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001046 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001047}
1048
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001049#if HUSH_DEBUG < 2
1050# undef die_if_script
1051# undef syntax_error
1052# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001053# undef syntax_error_unterm_ch
1054# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001055# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001056#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001057# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001058# define syntax_error(msg) syntax_error(__LINE__, msg)
1059# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1060# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1061# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1062# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001063#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001064
Denis Vlasenko552433b2009-04-04 19:29:21 +00001065
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001066#if ENABLE_HUSH_INTERACTIVE
1067static void cmdedit_update_prompt(void);
1068#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001069# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001070#endif
1071
1072
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001073/* Utility functions
1074 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001075/* Replace each \x with x in place, return ptr past NUL. */
1076static char *unbackslash(char *src)
1077{
Denys Vlasenko71885402009-09-24 01:44:13 +02001078 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001079 while (1) {
1080 if (*src == '\\')
1081 src++;
1082 if ((*dst++ = *src++) == '\0')
1083 break;
1084 }
1085 return dst;
1086}
1087
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001088static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001089{
1090 int i;
1091 unsigned count1;
1092 unsigned count2;
1093 char **v;
1094
1095 v = strings;
1096 count1 = 0;
1097 if (v) {
1098 while (*v) {
1099 count1++;
1100 v++;
1101 }
1102 }
1103 count2 = 0;
1104 v = add;
1105 while (*v) {
1106 count2++;
1107 v++;
1108 }
1109 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1110 v[count1 + count2] = NULL;
1111 i = count2;
1112 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001113 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001114 return v;
1115}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001116#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001117static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1118{
1119 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1120 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1121 return ptr;
1122}
1123#define add_strings_to_strings(strings, add, need_to_dup) \
1124 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1125#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001126
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001127/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001128static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001129{
1130 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001131 v[0] = add;
1132 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001133 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001134}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001135#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001136static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1137{
1138 char **ptr = add_string_to_strings(strings, add);
1139 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1140 return ptr;
1141}
1142#define add_string_to_strings(strings, add) \
1143 xx_add_string_to_strings(__LINE__, strings, add)
1144#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001145
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001146static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001147{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001148 char **v;
1149
1150 if (!strings)
1151 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001152 v = strings;
1153 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001154 free(*v);
1155 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001156 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001157 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001158}
1159
Denis Vlasenko76d50412008-06-10 16:19:39 +00001160
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001161/* Helpers for setting new $n and restoring them back
1162 */
1163typedef struct save_arg_t {
1164 char *sv_argv0;
1165 char **sv_g_argv;
1166 int sv_g_argc;
1167 smallint sv_g_malloced;
1168} save_arg_t;
1169
1170static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1171{
1172 int n;
1173
1174 sv->sv_argv0 = argv[0];
1175 sv->sv_g_argv = G.global_argv;
1176 sv->sv_g_argc = G.global_argc;
1177 sv->sv_g_malloced = G.global_args_malloced;
1178
1179 argv[0] = G.global_argv[0]; /* retain $0 */
1180 G.global_argv = argv;
1181 G.global_args_malloced = 0;
1182
1183 n = 1;
1184 while (*++argv)
1185 n++;
1186 G.global_argc = n;
1187}
1188
1189static void restore_G_args(save_arg_t *sv, char **argv)
1190{
1191 char **pp;
1192
1193 if (G.global_args_malloced) {
1194 /* someone ran "set -- arg1 arg2 ...", undo */
1195 pp = G.global_argv;
1196 while (*++pp) /* note: does not free $0 */
1197 free(*pp);
1198 free(G.global_argv);
1199 }
1200 argv[0] = sv->sv_argv0;
1201 G.global_argv = sv->sv_g_argv;
1202 G.global_argc = sv->sv_g_argc;
1203 G.global_args_malloced = sv->sv_g_malloced;
1204}
1205
1206
Denis Vlasenkod5762932009-03-31 11:22:57 +00001207/* Basic theory of signal handling in shell
1208 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001209 * This does not describe what hush does, rather, it is current understanding
1210 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001211 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1212 *
1213 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1214 * is finished or backgrounded. It is the same in interactive and
1215 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001216 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001217 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001218 * backgrounds (i.e. stops) or kills all members of currently running
1219 * pipe.
1220 *
1221 * Wait builtin in interruptible by signals for which user trap is set
1222 * or by SIGINT in interactive shell.
1223 *
1224 * Trap handlers will execute even within trap handlers. (right?)
1225 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001226 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1227 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001228 *
1229 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001230 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001231 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001232 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001233 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001234 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001235 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001236 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001237 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001238 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001239 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001240 *
1241 * SIGQUIT: ignore
1242 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001243 * SIGHUP (interactive):
1244 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001245 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001246 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1247 * that all pipe members are stopped. Try this in bash:
1248 * while :; do :; done - ^Z does not background it
1249 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001250 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001251 * of the command line, show prompt. NB: ^C does not send SIGINT
1252 * to interactive shell while shell is waiting for a pipe,
1253 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001254 * Example 1: this waits 5 sec, but does not execute ls:
1255 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1256 * Example 2: this does not wait and does not execute ls:
1257 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1258 * Example 3: this does not wait 5 sec, but executes ls:
1259 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001260 *
1261 * (What happens to signals which are IGN on shell start?)
1262 * (What happens with signal mask on shell start?)
1263 *
1264 * Implementation in hush
1265 * ======================
1266 * We use in-kernel pending signal mask to determine which signals were sent.
1267 * We block all signals which we don't want to take action immediately,
1268 * i.e. we block all signals which need to have special handling as described
1269 * above, and all signals which have traps set.
1270 * After each pipe execution, we extract any pending signals via sigtimedwait()
1271 * and act on them.
1272 *
1273 * unsigned non_DFL_mask: a mask of such "special" signals
1274 * sigset_t blocked_set: current blocked signal set
1275 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001276 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001277 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001278 * "trap 'cmd' SIGxxx":
1279 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001280 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001281 * unblock signals with special interactive handling
1282 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001283 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001284 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001285 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001286 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001287 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001288 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001289 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001290 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001291 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001292 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001293 * Standard says "When a subshell is entered, traps that are not being ignored
1294 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001295 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001296 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001297enum {
1298 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001299 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001300 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001301 | (1 << SIGHUP)
1302 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001303 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001304#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001305 | (1 << SIGTTIN)
1306 | (1 << SIGTTOU)
1307 | (1 << SIGTSTP)
1308#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001309};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001310
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001311#if ENABLE_HUSH_FAST
1312static void SIGCHLD_handler(int sig UNUSED_PARAM)
1313{
1314 G.count_SIGCHLD++;
1315//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1316}
1317#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001318
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001319#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001320
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001321/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001322# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001323/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001324# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001325
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001326/* Restores tty foreground process group, and exits.
1327 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001328 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001329 * or called directly with -EXITCODE.
1330 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001331static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001332static void sigexit(int sig)
1333{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001334 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001335 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001336
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001337 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001338 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001339 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1340 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001341
1342 /* Not a signal, just exit */
1343 if (sig <= 0)
1344 _exit(- sig);
1345
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001346 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001347}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001348#else
1349
Denys Vlasenko8391c482010-05-22 17:50:43 +02001350# define disable_restore_tty_pgrp_on_exit() ((void)0)
1351# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001352
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001353#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001354
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001355/* Restores tty foreground process group, and exits. */
1356static void hush_exit(int exitcode) NORETURN;
1357static void hush_exit(int exitcode)
1358{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001359 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1360 /* Prevent recursion:
1361 * trap "echo Hi; exit" EXIT; exit
1362 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001363 char *argv[3];
1364 /* argv[0] is unused */
1365 argv[1] = G.traps[0];
1366 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001367 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001368 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001369 * "trap" will still show it, if executed
1370 * in the handler */
1371 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001372 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001373
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001374#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001375 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001376 sigexit(- (exitcode & 0xff));
1377#else
1378 exit(exitcode);
1379#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001380}
1381
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001382
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001383static int check_and_run_traps(int sig)
1384{
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001385 /* I want it in rodata, not in bss.
1386 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1387 * initializer. But other compilers may still use bss.
1388 * TODO: find more portable solution.
1389 */
1390 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001391 smalluint save_rcode;
1392 int last_sig = 0;
1393
1394 if (sig)
1395 goto jump_in;
1396 while (1) {
1397 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1398 if (sig <= 0)
1399 break;
1400 jump_in:
1401 last_sig = sig;
1402 if (G.traps && G.traps[sig]) {
1403 if (G.traps[sig][0]) {
1404 /* We have user-defined handler */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001405 char *argv[3];
1406 /* argv[0] is unused */
1407 argv[1] = G.traps[sig];
1408 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001409 save_rcode = G.last_exitcode;
1410 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001411 G.last_exitcode = save_rcode;
1412 } /* else: "" trap, ignoring signal */
1413 continue;
1414 }
1415 /* not a trap: special action */
1416 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001417#if ENABLE_HUSH_FAST
1418 case SIGCHLD:
1419 G.count_SIGCHLD++;
1420//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1421 break;
1422#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001423 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001424 /* Builtin was ^C'ed, make it look prettier: */
1425 bb_putchar('\n');
1426 G.flag_SIGINT = 1;
1427 break;
1428#if ENABLE_HUSH_JOB
1429 case SIGHUP: {
1430 struct pipe *job;
1431 /* bash is observed to signal whole process groups,
1432 * not individual processes */
1433 for (job = G.job_list; job; job = job->next) {
1434 if (job->pgrp <= 0)
1435 continue;
1436 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1437 if (kill(- job->pgrp, SIGHUP) == 0)
1438 kill(- job->pgrp, SIGCONT);
1439 }
1440 sigexit(SIGHUP);
1441 }
1442#endif
1443 default: /* ignored: */
1444 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1445 break;
1446 }
1447 }
1448 return last_sig;
1449}
1450
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001451
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001452static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001453{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001454 if (force || G.cwd == NULL) {
1455 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1456 * we must not try to free(bb_msg_unknown) */
1457 if (G.cwd == bb_msg_unknown)
1458 G.cwd = NULL;
1459 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1460 if (!G.cwd)
1461 G.cwd = bb_msg_unknown;
1462 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001463 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001464}
1465
Denis Vlasenko83506862007-11-23 13:11:42 +00001466
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001467/*
1468 * Shell and environment variable support
1469 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001470static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001471{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001472 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001473 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001474
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001475 pp = &G.top_var;
1476 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001477 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001478 return pp;
1479 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001480 }
1481 return NULL;
1482}
1483
Denys Vlasenko03dad222010-01-12 23:29:57 +01001484static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001485{
Denys Vlasenko29082232010-07-16 13:52:32 +02001486 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001487 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001488
1489 if (G.expanded_assignments) {
1490 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001491 while (*cpp) {
1492 char *cp = *cpp;
1493 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1494 return cp + len + 1;
1495 cpp++;
1496 }
1497 }
1498
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001499 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001500 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001501 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001502
Denys Vlasenkodea47882009-10-09 15:40:49 +02001503 if (strcmp(name, "PPID") == 0)
1504 return utoa(G.root_ppid);
1505 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001506#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001507 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001508 return utoa(next_random(&G.random_gen));
1509#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001510 return NULL;
1511}
1512
1513/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001514 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001515 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001516 * 0: do not change export flag
1517 * (if creating new variable, flag will be 0)
1518 * 1: set export flag and putenv the variable
1519 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001520 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001521 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001522#if !BB_MMU && ENABLE_HUSH_LOCAL
1523/* all params are used */
1524#elif BB_MMU && ENABLE_HUSH_LOCAL
1525#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1526 set_local_var(str, flg_export, local_lvl)
1527#elif BB_MMU && !ENABLE_HUSH_LOCAL
1528#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001529 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001530#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1531#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1532 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001533#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001534static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001535{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001536 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001537 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001538 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001539 int name_len;
1540
Denis Vlasenko950bd722009-04-21 11:23:56 +00001541 eq_sign = strchr(str, '=');
1542 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001543 free(str);
1544 return -1;
1545 }
1546
Denis Vlasenko950bd722009-04-21 11:23:56 +00001547 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001548 var_pp = &G.top_var;
1549 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001550 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001551 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001552 continue;
1553 }
1554 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001555 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001556#if !BB_MMU
1557 if (!flg_read_only)
1558#endif
1559 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001560 free(str);
1561 return -1;
1562 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001563 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001564 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1565 *eq_sign = '\0';
1566 unsetenv(str);
1567 *eq_sign = '=';
1568 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001569#if ENABLE_HUSH_LOCAL
1570 if (cur->func_nest_level < local_lvl) {
1571 /* New variable is declared as local,
1572 * and existing one is global, or local
1573 * from enclosing function.
1574 * Remove and save old one: */
1575 *var_pp = cur->next;
1576 cur->next = *G.shadowed_vars_pp;
1577 *G.shadowed_vars_pp = cur;
1578 /* bash 3.2.33(1) and exported vars:
1579 * # export z=z
1580 * # f() { local z=a; env | grep ^z; }
1581 * # f
1582 * z=a
1583 * # env | grep ^z
1584 * z=z
1585 */
1586 if (cur->flg_export)
1587 flg_export = 1;
1588 break;
1589 }
1590#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001591 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001592 free_and_exp:
1593 free(str);
1594 goto exp;
1595 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001596 if (cur->max_len != 0) {
1597 if (cur->max_len >= strlen(str)) {
1598 /* This one is from startup env, reuse space */
1599 strcpy(cur->varstr, str);
1600 goto free_and_exp;
1601 }
1602 } else {
1603 /* max_len == 0 signifies "malloced" var, which we can
1604 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001605 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001606 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001607 cur->max_len = 0;
1608 goto set_str_and_exp;
1609 }
1610
Denys Vlasenko295fef82009-06-03 12:47:26 +02001611 /* Not found - create new variable struct */
1612 cur = xzalloc(sizeof(*cur));
1613#if ENABLE_HUSH_LOCAL
1614 cur->func_nest_level = local_lvl;
1615#endif
1616 cur->next = *var_pp;
1617 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001618
1619 set_str_and_exp:
1620 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001621#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001622 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001623#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001624 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001625 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001626 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001627 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1628 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001629 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001630 if (flg_export == -1) {
1631 cur->flg_export = 0;
1632 /* unsetenv was already done */
1633 } else {
1634 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1635 return putenv(cur->varstr);
1636 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001637 }
1638 return 0;
1639}
1640
Denys Vlasenko6db47842009-09-05 20:15:17 +02001641/* Used at startup and after each cd */
1642static void set_pwd_var(int exp)
1643{
1644 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1645 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1646}
1647
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001648static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001649{
1650 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001651 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001652
1653 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001654 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001655 var_pp = &G.top_var;
1656 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001657 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1658 if (cur->flg_read_only) {
1659 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001660 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001661 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001662 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001663 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1664 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001665 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1666 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001667 if (!cur->max_len)
1668 free(cur->varstr);
1669 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001670 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001671 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001672 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001673 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001674 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001675}
1676
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001677static int unset_local_var(const char *name)
1678{
1679 return unset_local_var_len(name, strlen(name));
1680}
1681
1682static void unset_vars(char **strings)
1683{
1684 char **v;
1685
1686 if (!strings)
1687 return;
1688 v = strings;
1689 while (*v) {
1690 const char *eq = strchrnul(*v, '=');
1691 unset_local_var_len(*v, (int)(eq - *v));
1692 v++;
1693 }
1694 free(strings);
1695}
1696
Denys Vlasenko03dad222010-01-12 23:29:57 +01001697static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001698{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001699 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001700 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001701}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001702
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001703
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001704/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001705 * Helpers for "var1=val1 var2=val2 cmd" feature
1706 */
1707static void add_vars(struct variable *var)
1708{
1709 struct variable *next;
1710
1711 while (var) {
1712 next = var->next;
1713 var->next = G.top_var;
1714 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001715 if (var->flg_export) {
1716 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001717 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001718 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001719 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001720 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001721 var = next;
1722 }
1723}
1724
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001725static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001726{
1727 char **s;
1728 struct variable *old = NULL;
1729
1730 if (!strings)
1731 return old;
1732 s = strings;
1733 while (*s) {
1734 struct variable *var_p;
1735 struct variable **var_pp;
1736 char *eq;
1737
1738 eq = strchr(*s, '=');
1739 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001740 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001741 if (var_pp) {
1742 /* Remove variable from global linked list */
1743 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001744 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001745 *var_pp = var_p->next;
1746 /* Add it to returned list */
1747 var_p->next = old;
1748 old = var_p;
1749 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001750 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001751 }
1752 s++;
1753 }
1754 return old;
1755}
1756
1757
1758/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001759 * in_str support
1760 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001761static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001762{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001763 int ch = *i->p;
1764 if (ch != '\0') {
1765 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001766 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001767 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001768 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001769}
1770
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001771static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001772{
1773 return *i->p;
1774}
1775
1776#if ENABLE_HUSH_INTERACTIVE
1777
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001778static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001779{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001780 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001781 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001782 if (G.PS1 == NULL)
1783 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001784 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001785 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001786 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001787 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001788 if (G.PS2 == NULL)
1789 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001790}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001791
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001792static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001793{
1794 const char *prompt_str;
1795 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001796 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1797 /* Set up the prompt */
1798 if (promptmode == 0) { /* PS1 */
1799 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001800 /* bash uses $PWD value, even if it is set by user.
1801 * It uses current dir only if PWD is unset.
1802 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001803 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001804 prompt_str = G.PS1;
1805 } else
1806 prompt_str = G.PS2;
1807 } else
1808 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001809 debug_printf("result '%s'\n", prompt_str);
1810 return prompt_str;
1811}
1812
1813static void get_user_input(struct in_str *i)
1814{
1815 int r;
1816 const char *prompt_str;
1817
1818 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001819# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001820 /* Enable command line editing only while a command line
1821 * is actually being read */
1822 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001823 G.flag_SIGINT = 0;
1824 /* buglet: SIGINT will not make new prompt to appear _at once_,
1825 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001826 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 +00001827 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001828 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001829 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001830 i->eof_flag = (r < 0);
1831 if (i->eof_flag) { /* EOF/error detected */
1832 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1833 G.user_input_buf[1] = '\0';
1834 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001835# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001836 do {
1837 G.flag_SIGINT = 0;
1838 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001839 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001840 G.user_input_buf[0] = r = fgetc(i->file);
1841 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001842//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001843 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001844 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001845# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001846 i->p = G.user_input_buf;
1847}
1848
1849#endif /* INTERACTIVE */
1850
1851/* This is the magic location that prints prompts
1852 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001853static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001854{
1855 int ch;
1856
1857 /* If there is data waiting, eat it up */
1858 if (i->p && *i->p) {
1859#if ENABLE_HUSH_INTERACTIVE
1860 take_cached:
1861#endif
1862 ch = *i->p++;
1863 if (i->eof_flag && !*i->p)
1864 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001865 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001866 } else {
1867 /* need to double check i->file because we might be doing something
1868 * more complicated by now, like sourcing or substituting. */
1869#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001870 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001871 do {
1872 get_user_input(i);
1873 } while (!*i->p); /* need non-empty line */
1874 i->promptmode = 1; /* PS2 */
1875 i->promptme = 0;
1876 goto take_cached;
1877 }
1878#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001879 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001880 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001881 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001882#if ENABLE_HUSH_INTERACTIVE
1883 if (ch == '\n')
1884 i->promptme = 1;
1885#endif
1886 return ch;
1887}
1888
Denis Vlasenko913a2012009-04-05 22:17:04 +00001889/* All callers guarantee this routine will never
1890 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001891 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001892static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001893{
1894 int ch;
1895 if (i->p && *i->p) {
1896 if (i->eof_flag && !i->p[1])
1897 return EOF;
1898 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001899 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001900 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001901 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001902 i->eof_flag = (ch == EOF);
1903 i->peek_buf[0] = ch;
1904 i->peek_buf[1] = '\0';
1905 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001906 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001907 return ch;
1908}
1909
1910static void setup_file_in_str(struct in_str *i, FILE *f)
1911{
1912 i->peek = file_peek;
1913 i->get = file_get;
1914#if ENABLE_HUSH_INTERACTIVE
1915 i->promptme = 1;
1916 i->promptmode = 0; /* PS1 */
1917#endif
1918 i->file = f;
1919 i->p = NULL;
1920}
1921
1922static void setup_string_in_str(struct in_str *i, const char *s)
1923{
1924 i->peek = static_peek;
1925 i->get = static_get;
1926#if ENABLE_HUSH_INTERACTIVE
1927 i->promptme = 1;
1928 i->promptmode = 0; /* PS1 */
1929#endif
1930 i->p = s;
1931 i->eof_flag = 0;
1932}
1933
1934
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001935/*
1936 * o_string support
1937 */
1938#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001939
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001940static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001941{
1942 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02001943 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001944 if (o->data)
1945 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001946}
1947
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001948static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001949{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001950 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001951 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001952}
1953
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001954static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1955{
1956 free(o->data);
1957}
1958
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001959static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001960{
1961 if (o->length + len > o->maxlen) {
1962 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1963 o->data = xrealloc(o->data, 1 + o->maxlen);
1964 }
1965}
1966
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001967static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001968{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001969 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1970 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001971 o->data[o->length] = ch;
1972 o->length++;
1973 o->data[o->length] = '\0';
1974}
1975
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001976static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001977{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001978 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001979 memcpy(&o->data[o->length], str, len);
1980 o->length += len;
1981 o->data[o->length] = '\0';
1982}
1983
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001984static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001985{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001986 o_addblock(o, str, strlen(str));
1987}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02001988
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001989#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001990static void nommu_addchr(o_string *o, int ch)
1991{
1992 if (o)
1993 o_addchr(o, ch);
1994}
1995#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001996# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001997#endif
1998
1999static void o_addstr_with_NUL(o_string *o, const char *str)
2000{
2001 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002002}
2003
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002004static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00002005{
2006 while (len) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002007 len--;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002008 o_addchr(o, *str);
2009 if (*str++ == '\\') {
2010 /* \z -> \\\z; \<eol> -> \\<eol> */
2011 o_addchr(o, '\\');
2012 if (len) {
2013 len--;
2014 o_addchr(o, '\\');
2015 o_addchr(o, *str++);
2016 }
2017 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002018 }
2019}
2020
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002021#undef HUSH_BRACE_EXP
2022/*
2023 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2024 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2025 * Apparently, on unquoted $v bash still does globbing
2026 * ("v='*.txt'; echo $v" prints all .txt files),
2027 * but NOT brace expansion! Thus, there should be TWO independent
2028 * quoting mechanisms on $v expansion side: one protects
2029 * $v from brace expansion, and other additionally protects "$v" against globbing.
2030 * We have only second one.
2031 */
2032
2033#ifdef HUSH_BRACE_EXP
2034# define MAYBE_BRACES "{}"
2035#else
2036# define MAYBE_BRACES ""
2037#endif
2038
Eric Andersen25f27032001-04-26 23:22:31 +00002039/* My analysis of quoting semantics tells me that state information
2040 * is associated with a destination, not a source.
2041 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002042static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002043{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002044 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002045 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002046 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002047 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002048 o_grow_by(o, sz);
2049 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002050 o->data[o->length] = '\\';
2051 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002052 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002053 o->data[o->length] = ch;
2054 o->length++;
2055 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002056}
2057
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002058static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002059{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002060 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002061 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2062 && strchr("*?[\\" MAYBE_BRACES, ch)
2063 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002064 sz++;
2065 o->data[o->length] = '\\';
2066 o->length++;
2067 }
2068 o_grow_by(o, sz);
2069 o->data[o->length] = ch;
2070 o->length++;
2071 o->data[o->length] = '\0';
2072}
2073
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002074static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002075{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002076 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002077 char ch;
2078 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002079 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002080 if (ordinary_cnt > len) /* paranoia */
2081 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002082 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002083 if (ordinary_cnt == len)
2084 return;
2085 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002086 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002087
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002088 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002089 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002090 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002091 sz++;
2092 o->data[o->length] = '\\';
2093 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002094 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002095 o_grow_by(o, sz);
2096 o->data[o->length] = ch;
2097 o->length++;
2098 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002099 }
2100}
2101
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002102static void o_addQblock(o_string *o, const char *str, int len)
2103{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002104 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002105 o_addblock(o, str, len);
2106 return;
2107 }
2108 o_addqblock(o, str, len);
2109}
2110
Denys Vlasenko38292b62010-09-05 14:49:40 +02002111static void o_addQstr(o_string *o, const char *str)
2112{
2113 o_addQblock(o, str, strlen(str));
2114}
2115
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002116/* A special kind of o_string for $VAR and `cmd` expansion.
2117 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002118 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002119 * list[i] contains an INDEX (int!) into this string data.
2120 * It means that if list[] needs to grow, data needs to be moved higher up
2121 * but list[i]'s need not be modified.
2122 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002123 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002124 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2125 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002126#if DEBUG_EXPAND || DEBUG_GLOB
2127static void debug_print_list(const char *prefix, o_string *o, int n)
2128{
2129 char **list = (char**)o->data;
2130 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2131 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002132
2133 indent();
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002134 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002135 prefix, list, n, string_start, o->length, o->maxlen,
2136 !!(o->o_expflags & EXP_FLAG_GLOB),
2137 o->has_quoted_part,
2138 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002139 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002140 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002141 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2142 o->data + (int)list[i] + string_start,
2143 o->data + (int)list[i] + string_start);
2144 i++;
2145 }
2146 if (n) {
2147 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002148 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002149 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002150 }
2151}
2152#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002153# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002154#endif
2155
2156/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2157 * in list[n] so that it points past last stored byte so far.
2158 * It returns n+1. */
2159static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002160{
2161 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002162 int string_start;
2163 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002164
2165 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002166 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2167 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002168 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002169 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002170 /* list[n] points to string_start, make space for 16 more pointers */
2171 o->maxlen += 0x10 * sizeof(list[0]);
2172 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002173 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002174 memmove(list + n + 0x10, list + n, string_len);
2175 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002176 } else {
2177 debug_printf_list("list[%d]=%d string_start=%d\n",
2178 n, string_len, string_start);
2179 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002180 } else {
2181 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002182 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2183 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002184 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2185 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002186 o->has_empty_slot = 0;
2187 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002188 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002189 return n + 1;
2190}
2191
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002192/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002193static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002194{
2195 char **list = (char**)o->data;
2196 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2197
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002198 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002199}
2200
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002201#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002202/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2203 * first, it processes even {a} (no commas), second,
2204 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002205 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002206 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002207
2208/* Helper */
2209static int glob_needed(const char *s)
2210{
2211 while (*s) {
2212 if (*s == '\\') {
2213 if (!s[1])
2214 return 0;
2215 s += 2;
2216 continue;
2217 }
2218 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2219 return 1;
2220 s++;
2221 }
2222 return 0;
2223}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002224/* Return pointer to next closing brace or to comma */
2225static const char *next_brace_sub(const char *cp)
2226{
2227 unsigned depth = 0;
2228 cp++;
2229 while (*cp != '\0') {
2230 if (*cp == '\\') {
2231 if (*++cp == '\0')
2232 break;
2233 cp++;
2234 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002235 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002236 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002237 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002238 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002239 depth++;
2240 }
2241
2242 return *cp != '\0' ? cp : NULL;
2243}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002244/* Recursive brace globber. Note: may garble pattern[]. */
2245static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002246{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002247 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002248 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002249 const char *next;
2250 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002251 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002252 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002253
2254 debug_printf_glob("glob_brace('%s')\n", pattern);
2255
2256 begin = pattern;
2257 while (1) {
2258 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002259 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002260 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002261 /* Find the first sub-pattern and at the same time
2262 * find the rest after the closing brace */
2263 next = next_brace_sub(begin);
2264 if (next == NULL) {
2265 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002266 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002267 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002268 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002269 /* "{abc}" with no commas - illegal
2270 * brace expr, disregard and skip it */
2271 begin = next + 1;
2272 continue;
2273 }
2274 break;
2275 }
2276 if (*begin == '\\' && begin[1] != '\0')
2277 begin++;
2278 begin++;
2279 }
2280 debug_printf_glob("begin:%s\n", begin);
2281 debug_printf_glob("next:%s\n", next);
2282
2283 /* Now find the end of the whole brace expression */
2284 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002285 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002286 rest = next_brace_sub(rest);
2287 if (rest == NULL) {
2288 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002289 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002290 }
2291 debug_printf_glob("rest:%s\n", rest);
2292 }
2293 rest_len = strlen(++rest) + 1;
2294
2295 /* We are sure the brace expression is well-formed */
2296
2297 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002298 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002299
2300 /* We have a brace expression. BEGIN points to the opening {,
2301 * NEXT points past the terminator of the first element, and REST
2302 * points past the final }. We will accumulate result names from
2303 * recursive runs for each brace alternative in the buffer using
2304 * GLOB_APPEND. */
2305
2306 p = begin + 1;
2307 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002308 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002309 memcpy(
2310 mempcpy(
2311 mempcpy(new_pattern_buf,
2312 /* We know the prefix for all sub-patterns */
2313 pattern, begin - pattern),
2314 p, next - p),
2315 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002316
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002317 /* Note: glob_brace() may garble new_pattern_buf[].
2318 * That's why we re-copy prefix every time (1st memcpy above).
2319 */
2320 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002321 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002322 /* We saw the last entry */
2323 break;
2324 }
2325 p = next + 1;
2326 next = next_brace_sub(next);
2327 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002328 free(new_pattern_buf);
2329 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002330
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002331 simple_glob:
2332 {
2333 int gr;
2334 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002335
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002336 memset(&globdata, 0, sizeof(globdata));
2337 gr = glob(pattern, 0, NULL, &globdata);
2338 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2339 if (gr != 0) {
2340 if (gr == GLOB_NOMATCH) {
2341 globfree(&globdata);
2342 /* NB: garbles parameter */
2343 unbackslash(pattern);
2344 o_addstr_with_NUL(o, pattern);
2345 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2346 return o_save_ptr_helper(o, n);
2347 }
2348 if (gr == GLOB_NOSPACE)
2349 bb_error_msg_and_die(bb_msg_memory_exhausted);
2350 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2351 * but we didn't specify it. Paranoia again. */
2352 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2353 }
2354 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2355 char **argv = globdata.gl_pathv;
2356 while (1) {
2357 o_addstr_with_NUL(o, *argv);
2358 n = o_save_ptr_helper(o, n);
2359 argv++;
2360 if (!*argv)
2361 break;
2362 }
2363 }
2364 globfree(&globdata);
2365 }
2366 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002367}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002368/* Performs globbing on last list[],
2369 * saving each result as a new list[].
2370 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002371static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002372{
2373 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002374
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002375 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002376 if (!o->data)
2377 return o_save_ptr_helper(o, n);
2378 pattern = o->data + o_get_last_ptr(o, n);
2379 debug_printf_glob("glob pattern '%s'\n", pattern);
2380 if (!glob_needed(pattern)) {
2381 /* unbackslash last string in o in place, fix length */
2382 o->length = unbackslash(pattern) - o->data;
2383 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2384 return o_save_ptr_helper(o, n);
2385 }
2386
2387 copy = xstrdup(pattern);
2388 /* "forget" pattern in o */
2389 o->length = pattern - o->data;
2390 n = glob_brace(copy, o, n);
2391 free(copy);
2392 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002393 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002394 return n;
2395}
2396
Denys Vlasenko8391c482010-05-22 17:50:43 +02002397#else /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002398
2399/* Helper */
2400static int glob_needed(const char *s)
2401{
2402 while (*s) {
2403 if (*s == '\\') {
2404 if (!s[1])
2405 return 0;
2406 s += 2;
2407 continue;
2408 }
2409 if (*s == '*' || *s == '[' || *s == '?')
2410 return 1;
2411 s++;
2412 }
2413 return 0;
2414}
2415/* Performs globbing on last list[],
2416 * saving each result as a new list[].
2417 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002418static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002419{
2420 glob_t globdata;
2421 int gr;
2422 char *pattern;
2423
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002424 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002425 if (!o->data)
2426 return o_save_ptr_helper(o, n);
2427 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002428 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002429 if (!glob_needed(pattern)) {
2430 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002431 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002432 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002433 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002434 return o_save_ptr_helper(o, n);
2435 }
2436
2437 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002438 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2439 * If we glob "*.\*" and don't find anything, we need
2440 * to fall back to using literal "*.*", but GLOB_NOCHECK
2441 * will return "*.\*"!
2442 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002443 gr = glob(pattern, 0, NULL, &globdata);
2444 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002445 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002446 if (gr == GLOB_NOMATCH) {
2447 globfree(&globdata);
2448 goto literal;
2449 }
2450 if (gr == GLOB_NOSPACE)
2451 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002452 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2453 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002454 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002455 }
2456 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2457 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002458 /* "forget" pattern in o */
2459 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002460 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002461 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002462 n = o_save_ptr_helper(o, n);
2463 argv++;
2464 if (!*argv)
2465 break;
2466 }
2467 }
2468 globfree(&globdata);
2469 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002470 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002471 return n;
2472}
2473
Denys Vlasenko8391c482010-05-22 17:50:43 +02002474#endif /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002475
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002476/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002477 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002478static int o_save_ptr(o_string *o, int n)
2479{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002480 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002481 /* If o->has_empty_slot, list[n] was already globbed
2482 * (if it was requested back then when it was filled)
2483 * so don't do that again! */
2484 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002485 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002486 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002487 return o_save_ptr_helper(o, n);
2488}
2489
2490/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002491static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002492{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002493 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002494 int string_start;
2495
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002496 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2497 if (DEBUG_EXPAND)
2498 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002499 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002500 list = (char**)o->data;
2501 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2502 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002503 while (n) {
2504 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002505 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002506 }
2507 return list;
2508}
2509
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002510static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002511
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002512/* Returns pi->next - next pipe in the list */
2513static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002514{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002515 struct pipe *next;
2516 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002517
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002518 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002519 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002520 struct command *command;
2521 struct redir_struct *r, *rnext;
2522
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002523 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002524 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002525 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002526 if (DEBUG_CLEAN) {
2527 int a;
2528 char **p;
2529 for (a = 0, p = command->argv; *p; a++, p++) {
2530 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2531 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002532 }
2533 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002534 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002535 }
2536 /* not "else if": on syntax error, we may have both! */
2537 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002538 debug_printf_clean(" begin group (cmd_type:%d)\n",
2539 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002540 free_pipe_list(command->group);
2541 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002542 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002543 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002544 /* else is crucial here.
2545 * If group != NULL, child_func is meaningless */
2546#if ENABLE_HUSH_FUNCTIONS
2547 else if (command->child_func) {
2548 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2549 command->child_func->parent_cmd = NULL;
2550 }
2551#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002552#if !BB_MMU
2553 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002554 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002555#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002557 debug_printf_clean(" redirect %d%s",
2558 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002559 /* guard against the case >$FOO, where foo is unset or blank */
2560 if (r->rd_filename) {
2561 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2562 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002563 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002564 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002565 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002566 rnext = r->next;
2567 free(r);
2568 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002569 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002570 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002571 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002572 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002573#if ENABLE_HUSH_JOB
2574 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002575 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002576#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002577
2578 next = pi->next;
2579 free(pi);
2580 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002581}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002582
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002583static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002584{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002585 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002586#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002587 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002588#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002589 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002590 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002591 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002592}
2593
2594
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002595/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002596
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002597static struct pipe *new_pipe(void)
2598{
Eric Andersen25f27032001-04-26 23:22:31 +00002599 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002600 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002601 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002602 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002603 return pi;
2604}
2605
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002606/* Command (member of a pipe) is complete, or we start a new pipe
2607 * if ctx->command is NULL.
2608 * No errors possible here.
2609 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002610static int done_command(struct parse_context *ctx)
2611{
2612 /* The command is really already in the pipe structure, so
2613 * advance the pipe counter and make a new, null command. */
2614 struct pipe *pi = ctx->pipe;
2615 struct command *command = ctx->command;
2616
2617 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002618 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002619 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002620 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002621 }
2622 pi->num_cmds++;
2623 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002624 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002625 } else {
2626 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2627 }
2628
2629 /* Only real trickiness here is that the uncommitted
2630 * command structure is not counted in pi->num_cmds. */
2631 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002632 ctx->command = command = &pi->cmds[pi->num_cmds];
2633 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002634 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002635 return pi->num_cmds; /* used only for 0/nonzero check */
2636}
2637
2638static void done_pipe(struct parse_context *ctx, pipe_style type)
2639{
2640 int not_null;
2641
2642 debug_printf_parse("done_pipe entered, followup %d\n", type);
2643 /* Close previous command */
2644 not_null = done_command(ctx);
2645 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002646#if HAS_KEYWORDS
2647 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2648 ctx->ctx_inverted = 0;
2649 ctx->pipe->res_word = ctx->ctx_res_w;
2650#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002651
2652 /* Without this check, even just <enter> on command line generates
2653 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002654 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002655 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002656#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002657 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002658#endif
2659#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002660 || ctx->ctx_res_w == RES_DONE
2661 || ctx->ctx_res_w == RES_FOR
2662 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002663#endif
2664#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002665 || ctx->ctx_res_w == RES_ESAC
2666#endif
2667 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002668 struct pipe *new_p;
2669 debug_printf_parse("done_pipe: adding new pipe: "
2670 "not_null:%d ctx->ctx_res_w:%d\n",
2671 not_null, ctx->ctx_res_w);
2672 new_p = new_pipe();
2673 ctx->pipe->next = new_p;
2674 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002675 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002676 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002677 * This is used to control execution.
2678 * RES_FOR and RES_IN are NOT sticky (needed to support
2679 * cases where variable or value happens to match a keyword):
2680 */
2681#if ENABLE_HUSH_LOOPS
2682 if (ctx->ctx_res_w == RES_FOR
2683 || ctx->ctx_res_w == RES_IN)
2684 ctx->ctx_res_w = RES_NONE;
2685#endif
2686#if ENABLE_HUSH_CASE
2687 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002688 ctx->ctx_res_w = RES_CASE_BODY;
2689 if (ctx->ctx_res_w == RES_CASE)
2690 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002691#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002692 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002693 /* Create the memory for command, roughly:
2694 * ctx->pipe->cmds = new struct command;
2695 * ctx->command = &ctx->pipe->cmds[0];
2696 */
2697 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002698 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002699 }
2700 debug_printf_parse("done_pipe return\n");
2701}
2702
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002703static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002704{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002705 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002706 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002707 /* Create the memory for command, roughly:
2708 * ctx->pipe->cmds = new struct command;
2709 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002710 */
2711 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002712}
2713
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002714/* If a reserved word is found and processed, parse context is modified
2715 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002716 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002717#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002718struct reserved_combo {
2719 char literal[6];
2720 unsigned char res;
2721 unsigned char assignment_flag;
2722 int flag;
2723};
2724enum {
2725 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002726# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002727 FLAG_IF = (1 << RES_IF ),
2728 FLAG_THEN = (1 << RES_THEN ),
2729 FLAG_ELIF = (1 << RES_ELIF ),
2730 FLAG_ELSE = (1 << RES_ELSE ),
2731 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002732# endif
2733# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002734 FLAG_FOR = (1 << RES_FOR ),
2735 FLAG_WHILE = (1 << RES_WHILE),
2736 FLAG_UNTIL = (1 << RES_UNTIL),
2737 FLAG_DO = (1 << RES_DO ),
2738 FLAG_DONE = (1 << RES_DONE ),
2739 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002740# endif
2741# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002742 FLAG_MATCH = (1 << RES_MATCH),
2743 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002744# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002745 FLAG_START = (1 << RES_XXXX ),
2746};
2747
2748static const struct reserved_combo* match_reserved_word(o_string *word)
2749{
Eric Andersen25f27032001-04-26 23:22:31 +00002750 /* Mostly a list of accepted follow-up reserved words.
2751 * FLAG_END means we are done with the sequence, and are ready
2752 * to turn the compound list into a command.
2753 * FLAG_START means the word must start a new compound list.
2754 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002755 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002756# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002757 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2758 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2759 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2760 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2761 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2762 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002763# endif
2764# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002765 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2766 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2767 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2768 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2769 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2770 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002771# endif
2772# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002773 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2774 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002775# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002776 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002777 const struct reserved_combo *r;
2778
2779 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2780 if (strcmp(word->data, r->literal) == 0)
2781 return r;
2782 }
2783 return NULL;
2784}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002785/* Return 0: not a keyword, 1: keyword
2786 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002787static int reserved_word(o_string *word, struct parse_context *ctx)
2788{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002789# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002790 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002791 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002792 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002793# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002794 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002795
Denys Vlasenko38292b62010-09-05 14:49:40 +02002796 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002797 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002798 r = match_reserved_word(word);
2799 if (!r)
2800 return 0;
2801
2802 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002803# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002804 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2805 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002806 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002807 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002808# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002809 if (r->flag == 0) { /* '!' */
2810 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002811 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002812 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002813 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002814 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002815 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002816 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002817 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002818 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002819
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002820 old = xmalloc(sizeof(*old));
2821 debug_printf_parse("push stack %p\n", old);
2822 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002823 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002824 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002825 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002826 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002827 ctx->ctx_res_w = RES_SNTX;
2828 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002829 } else {
2830 /* "{...} fi" is ok. "{...} if" is not
2831 * Example:
2832 * if { echo foo; } then { echo bar; } fi */
2833 if (ctx->command->group)
2834 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002835 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002836
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002837 ctx->ctx_res_w = r->res;
2838 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002839 word->o_assignment = r->assignment_flag;
2840
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002841 if (ctx->old_flag & FLAG_END) {
2842 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002843
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002844 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002845 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002846 old = ctx->stack;
2847 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002848 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002849# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002850 o_addstr(&old->as_string, ctx->as_string.data);
2851 o_free_unsafe(&ctx->as_string);
2852 old->command->group_as_string = xstrdup(old->as_string.data);
2853 debug_printf_parse("pop, remembering as:'%s'\n",
2854 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002855# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002856 *ctx = *old; /* physical copy */
2857 free(old);
2858 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002859 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002860}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002861#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00002862
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002863/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002864 * Normal return is 0. Syntax errors return 1.
2865 * Note: on return, word is reset, but not o_free'd!
2866 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002867static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002868{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002869 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00002870
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002871 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02002872 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002873 debug_printf_parse("done_word return 0: true null, ignored\n");
2874 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002875 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002876
Eric Andersen25f27032001-04-26 23:22:31 +00002877 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002878 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2879 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002880 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2881 * "2.7 Redirection
2882 * ...the word that follows the redirection operator
2883 * shall be subjected to tilde expansion, parameter expansion,
2884 * command substitution, arithmetic expansion, and quote
2885 * removal. Pathname expansion shall not be performed
2886 * on the word by a non-interactive shell; an interactive
2887 * shell may perform it, but shall do so only when
2888 * the expansion would result in one word."
2889 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002890 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002891 /* Cater for >\file case:
2892 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2893 * Same with heredocs:
2894 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2895 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002896 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2897 unbackslash(ctx->pending_redirect->rd_filename);
2898 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02002899 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002900 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2901 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002902 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002903 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002904 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002905 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002906 /* If this word wasn't an assignment, next ones definitely
2907 * can't be assignments. Even if they look like ones. */
2908 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2909 && word->o_assignment != WORD_IS_KEYWORD
2910 ) {
2911 word->o_assignment = NOT_ASSIGNMENT;
2912 } else {
2913 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2914 command->assignment_cnt++;
2915 word->o_assignment = MAYBE_ASSIGNMENT;
2916 }
2917
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002918#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002919# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00002920 if (ctx->ctx_dsemicolon
2921 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2922 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00002923 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002924 /* ctx->ctx_res_w = RES_MATCH; */
2925 ctx->ctx_dsemicolon = 0;
2926 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002927# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002928 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002929# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002930 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2931 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002932# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002933# if ENABLE_HUSH_CASE
2934 && ctx->ctx_res_w != RES_CASE
2935# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002936 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002937 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002938 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002939 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002940 debug_printf_parse("done_word return %d\n",
2941 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002942 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002943 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002944# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002945 if (strcmp(word->data, "[[") == 0) {
2946 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2947 }
2948 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002949# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002950 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002951#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00002952 if (command->group) {
2953 /* "{ echo foo; } echo bar" - bad */
2954 syntax_error_at(word->data);
2955 debug_printf_parse("done_word return 1: syntax error, "
2956 "groups and arglists don't mix\n");
2957 return 1;
2958 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02002959 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00002960 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2961 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002962 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002963 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002964 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002965 char *p = word->data;
2966 while (p[0] == SPECIAL_VAR_SYMBOL
2967 && (p[1] & 0x7f) == '@'
2968 && p[2] == SPECIAL_VAR_SYMBOL
2969 ) {
2970 p += 3;
2971 }
2972 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002973 /* saw no "$@", or not only "$@" but some
2974 * real text is there too */
2975 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002976 * e.g. "", $empty"" etc to not disappear */
2977 o_addchr(word, SPECIAL_VAR_SYMBOL);
2978 o_addchr(word, SPECIAL_VAR_SYMBOL);
2979 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002980 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002981 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002982 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002983 }
Eric Andersen25f27032001-04-26 23:22:31 +00002984
Denis Vlasenko06810332007-05-21 23:30:54 +00002985#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002986 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02002987 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002988 || !is_well_formed_var_name(command->argv[0], '\0')
2989 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002990 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002991 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002992 return 1;
2993 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002994 /* Force FOR to have just one word (variable name) */
2995 /* NB: basically, this makes hush see "for v in ..."
2996 * syntax as if it is "for v; in ...". FOR and IN become
2997 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002998 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002999 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003000#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003001#if ENABLE_HUSH_CASE
3002 /* Force CASE to have just one word */
3003 if (ctx->ctx_res_w == RES_CASE) {
3004 done_pipe(ctx, PIPE_SEQ);
3005 }
3006#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003007
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003008 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003009
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003010 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003011 return 0;
3012}
3013
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003014
3015/* Peek ahead in the input to find out if we have a "&n" construct,
3016 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003017 * Return:
3018 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3019 * REDIRFD_SYNTAX_ERR if syntax error,
3020 * REDIRFD_TO_FILE if no & was seen,
3021 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003022 */
3023#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003024#define parse_redir_right_fd(as_string, input) \
3025 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003026#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003027static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003028{
3029 int ch, d, ok;
3030
3031 ch = i_peek(input);
3032 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003033 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003034
3035 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003036 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003037 ch = i_peek(input);
3038 if (ch == '-') {
3039 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003040 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003041 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003042 }
3043 d = 0;
3044 ok = 0;
3045 while (ch != EOF && isdigit(ch)) {
3046 d = d*10 + (ch-'0');
3047 ok = 1;
3048 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003049 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003050 ch = i_peek(input);
3051 }
3052 if (ok) return d;
3053
3054//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3055
3056 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003057 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003058}
3059
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003060/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003061 */
3062static int parse_redirect(struct parse_context *ctx,
3063 int fd,
3064 redir_type style,
3065 struct in_str *input)
3066{
3067 struct command *command = ctx->command;
3068 struct redir_struct *redir;
3069 struct redir_struct **redirp;
3070 int dup_num;
3071
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003072 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003073 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003074 /* Check for a '>&1' type redirect */
3075 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3076 if (dup_num == REDIRFD_SYNTAX_ERR)
3077 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003078 } else {
3079 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003080 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003081 if (dup_num) { /* <<-... */
3082 ch = i_getch(input);
3083 nommu_addchr(&ctx->as_string, ch);
3084 ch = i_peek(input);
3085 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003086 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003087
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003088 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003089 int ch = i_peek(input);
3090 if (ch == '|') {
3091 /* >|FILE redirect ("clobbering" >).
3092 * Since we do not support "set -o noclobber" yet,
3093 * >| and > are the same for now. Just eat |.
3094 */
3095 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003096 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003097 }
3098 }
3099
3100 /* Create a new redir_struct and append it to the linked list */
3101 redirp = &command->redirects;
3102 while ((redir = *redirp) != NULL) {
3103 redirp = &(redir->next);
3104 }
3105 *redirp = redir = xzalloc(sizeof(*redir));
3106 /* redir->next = NULL; */
3107 /* redir->rd_filename = NULL; */
3108 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003109 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003110
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003111 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3112 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003113
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003114 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003115 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003116 /* Erik had a check here that the file descriptor in question
3117 * is legit; I postpone that to "run time"
3118 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003119 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3120 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003121 } else {
3122 /* Set ctx->pending_redirect, so we know what to do at the
3123 * end of the next parsed word. */
3124 ctx->pending_redirect = redir;
3125 }
3126 return 0;
3127}
3128
Eric Andersen25f27032001-04-26 23:22:31 +00003129/* If a redirect is immediately preceded by a number, that number is
3130 * supposed to tell which file descriptor to redirect. This routine
3131 * looks for such preceding numbers. In an ideal world this routine
3132 * needs to handle all the following classes of redirects...
3133 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3134 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3135 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3136 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003137 *
3138 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3139 * "2.7 Redirection
3140 * ... If n is quoted, the number shall not be recognized as part of
3141 * the redirection expression. For example:
3142 * echo \2>a
3143 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003144 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003145 *
3146 * A -1 return means no valid number was found,
3147 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003148 */
3149static int redirect_opt_num(o_string *o)
3150{
3151 int num;
3152
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003153 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003154 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003155 num = bb_strtou(o->data, NULL, 10);
3156 if (errno || num < 0)
3157 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003158 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003159 return num;
3160}
3161
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003162#if BB_MMU
3163#define fetch_till_str(as_string, input, word, skip_tabs) \
3164 fetch_till_str(input, word, skip_tabs)
3165#endif
3166static char *fetch_till_str(o_string *as_string,
3167 struct in_str *input,
3168 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003169 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003170{
3171 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003172 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003173 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003174 int ch;
3175
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003176 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003177 while (1) {
3178 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003179 if (ch != EOF)
3180 nommu_addchr(as_string, ch);
3181 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003182 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3183 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003184 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3185 heredoc.data[past_EOL] = '\0';
3186 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3187 return heredoc.data;
3188 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003189 while (ch == '\n') {
3190 o_addchr(&heredoc, ch);
3191 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003192 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003193 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003194 do {
3195 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003196 if (ch != EOF)
3197 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003198 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003199 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003200 }
3201 if (ch == EOF) {
3202 o_free_unsafe(&heredoc);
3203 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003204 }
3205 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003206 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003207 if (prev == '\\' && ch == '\\')
3208 /* Correctly handle foo\\<eol> (not a line cont.) */
3209 prev = 0; /* not \ */
3210 else
3211 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003212 }
3213}
3214
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003215/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3216 * and load them all. There should be exactly heredoc_cnt of them.
3217 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003218static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3219{
3220 struct pipe *pi = ctx->list_head;
3221
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003222 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003223 int i;
3224 struct command *cmd = pi->cmds;
3225
3226 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3227 pi->num_cmds,
3228 cmd->argv ? cmd->argv[0] : "NONE");
3229 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003230 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003231
3232 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3233 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003234 while (redir) {
3235 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003236 char *p;
3237
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003238 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003239 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003240 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003241 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003242 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003243 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003244 return 1;
3245 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003246 free(redir->rd_filename);
3247 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003248 heredoc_cnt--;
3249 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003250 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003251 }
3252 cmd++;
3253 }
3254 pi = pi->next;
3255 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003256#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003257 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003258 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003259 bb_error_msg_and_die("heredoc BUG 2");
3260#endif
3261 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003262}
3263
3264
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003265static int run_list(struct pipe *pi);
3266#if BB_MMU
3267#define parse_stream(pstring, input, end_trigger) \
3268 parse_stream(input, end_trigger)
3269#endif
3270static struct pipe *parse_stream(char **pstring,
3271 struct in_str *input,
3272 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003273
Eric Andersen25f27032001-04-26 23:22:31 +00003274
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003275#if !ENABLE_HUSH_FUNCTIONS
3276#define parse_group(dest, ctx, input, ch) \
3277 parse_group(ctx, input, ch)
3278#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003279static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003280 struct in_str *input, int ch)
3281{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003282 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003283 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003284 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003285 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003286 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003287 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003288
3289 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003290#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003291 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003292 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003293 if (done_word(dest, ctx))
3294 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003295 if (!command->argv)
3296 goto skip; /* (... */
3297 if (command->argv[1]) { /* word word ... (... */
3298 syntax_error_unexpected_ch('(');
3299 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003300 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003301 /* it is "word(..." or "word (..." */
3302 do
3303 ch = i_getch(input);
3304 while (ch == ' ' || ch == '\t');
3305 if (ch != ')') {
3306 syntax_error_unexpected_ch(ch);
3307 return 1;
3308 }
3309 nommu_addchr(&ctx->as_string, ch);
3310 do
3311 ch = i_getch(input);
3312 while (ch == ' ' || ch == '\t' || ch == '\n');
3313 if (ch != '{') {
3314 syntax_error_unexpected_ch(ch);
3315 return 1;
3316 }
3317 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003318 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003319 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003320 }
3321#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003322
3323#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003324 if (command->argv /* word [word]{... */
3325 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003326 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003327 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003328 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003329 debug_printf_parse("parse_group return 1: "
3330 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003331 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003332 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003333#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003334
3335#if ENABLE_HUSH_FUNCTIONS
3336 skip:
3337#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003338 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003339 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003340 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003341 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003342 } else {
3343 /* bash does not allow "{echo...", requires whitespace */
3344 ch = i_getch(input);
3345 if (ch != ' ' && ch != '\t' && ch != '\n') {
3346 syntax_error_unexpected_ch(ch);
3347 return 1;
3348 }
3349 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003350 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003351
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003352 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003353#if BB_MMU
3354# define as_string NULL
3355#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003356 char *as_string = NULL;
3357#endif
3358 pipe_list = parse_stream(&as_string, input, endch);
3359#if !BB_MMU
3360 if (as_string)
3361 o_addstr(&ctx->as_string, as_string);
3362#endif
3363 /* empty ()/{} or parse error? */
3364 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003365 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003366 if (!BB_MMU)
3367 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003368 debug_printf_parse("parse_group return 1: "
3369 "parse_stream returned %p\n", pipe_list);
3370 return 1;
3371 }
3372 command->group = pipe_list;
3373#if !BB_MMU
3374 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3375 command->group_as_string = as_string;
3376 debug_printf_parse("end of group, remembering as:'%s'\n",
3377 command->group_as_string);
3378#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003379#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003380 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003381 debug_printf_parse("parse_group return 0\n");
3382 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003383 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003384}
3385
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003386#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003387/* Subroutines for copying $(...) and `...` things */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003388static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003389/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003390static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003391{
3392 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003393 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003394 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003395 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003396 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003397 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003398 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003399 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003400 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003401 }
3402}
3403/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003404static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003405{
3406 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003407 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003408 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003409 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003410 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003411 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003412 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003413 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003414 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003415 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003416 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003417 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003418 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003419 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003420 add_till_backquote(dest, input, /*in_dquote:*/ 1);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003421 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003422 continue;
3423 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003424 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003425 }
3426}
3427/* Process `cmd` - copy contents until "`" is seen. Complicated by
3428 * \` quoting.
3429 * "Within the backquoted style of command substitution, backslash
3430 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3431 * The search for the matching backquote shall be satisfied by the first
3432 * backquote found without a preceding backslash; during this search,
3433 * if a non-escaped backquote is encountered within a shell comment,
3434 * a here-document, an embedded command substitution of the $(command)
3435 * form, or a quoted string, undefined results occur. A single-quoted
3436 * or double-quoted string that begins, but does not end, within the
3437 * "`...`" sequence produces undefined results."
3438 * Example Output
3439 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3440 */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003441static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003442{
3443 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003444 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003445 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003446 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003447 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003448 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3449 ch = i_getch(input);
3450 if (ch != '`'
3451 && ch != '$'
3452 && ch != '\\'
3453 && (!in_dquote || ch != '"')
3454 ) {
3455 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003456 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003457 }
3458 if (ch == EOF) {
3459 syntax_error_unterm_ch('`');
3460 /*xfunc_die(); - redundant */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003461 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003462 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003463 }
3464}
3465/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3466 * quoting and nested ()s.
3467 * "With the $(command) style of command substitution, all characters
3468 * following the open parenthesis to the matching closing parenthesis
3469 * constitute the command. Any valid shell script can be used for command,
3470 * except a script consisting solely of redirections which produces
3471 * unspecified results."
3472 * Example Output
3473 * echo $(echo '(TEST)' BEST) (TEST) BEST
3474 * echo $(echo 'TEST)' BEST) TEST) BEST
3475 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003476 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003477 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003478 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003479 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3480 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003481 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003482#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003483static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003484{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003485 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003486 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003487# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003488 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003489# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003490 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3491
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003492 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003493 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003494 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003495 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003496 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003497 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003498 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003499 if (!dbl)
3500 break;
3501 /* we look for closing )) of $((EXPR)) */
3502 if (i_peek(input) == end_ch) {
3503 i_getch(input); /* eat second ')' */
3504 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003505 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003506 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003507 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003508 if (ch == '(' || ch == '{') {
3509 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003510 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003511 o_addchr(dest, ch);
3512 continue;
3513 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003514 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003515 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003516 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003517 continue;
3518 }
3519 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003520 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003521 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003522 continue;
3523 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003524 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003525 add_till_backquote(dest, input, /*in_dquote:*/ 0);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003526 o_addchr(dest, ch);
3527 continue;
3528 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003529 if (ch == '\\') {
3530 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003531 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003532 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003533 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003534 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003535 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003536 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003537 continue;
3538 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003539 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003540 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003541}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003542#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003543
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003544/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003545#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003546#define parse_dollar(as_string, dest, input, quote_mask) \
3547 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003548#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003549#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003550static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003551 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003552 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003553{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003554 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003555
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003556 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003557 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003558 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003559 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003560 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003561 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003562 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003563 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003564 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003565 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003566 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003567 if (!isalnum(ch) && ch != '_')
3568 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003569 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003570 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003571 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003572 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003573 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003574 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003575 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003576 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003577 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003578 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003579 o_addchr(dest, ch | quote_mask);
3580 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003581 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003582 case '$': /* pid */
3583 case '!': /* last bg pid */
3584 case '?': /* last exit code */
3585 case '#': /* number of args */
3586 case '*': /* args */
3587 case '@': /* args */
3588 goto make_one_char_var;
3589 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003590 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3591
Denys Vlasenko74369502010-05-21 19:52:01 +02003592 ch = i_getch(input); /* eat '{' */
3593 nommu_addchr(as_string, ch);
3594
3595 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003596 /* It should be ${?}, or ${#var},
3597 * or even ${?+subst} - operator acting on a special variable,
3598 * or the beginning of variable name.
3599 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003600 if (ch == EOF
3601 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3602 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003603 bad_dollar_syntax:
3604 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003605 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003606 return 1;
3607 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003608 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003609 ch |= quote_mask;
3610
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003611 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003612 * However, this regresses some of our testsuite cases
3613 * which check invalid constructs like ${%}.
3614 * Oh well... let's check that the var name part is fine... */
3615
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003616 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003617 unsigned pos;
3618
Denys Vlasenko74369502010-05-21 19:52:01 +02003619 o_addchr(dest, ch);
3620 debug_printf_parse(": '%c'\n", ch);
3621
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003622 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003623 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003624 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003625 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003626
Denys Vlasenko74369502010-05-21 19:52:01 +02003627 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003628 unsigned end_ch;
3629 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003630 /* handle parameter expansions
3631 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3632 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003633 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003634 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003635
3636 /* Eat everything until closing '}' (or ':') */
3637 end_ch = '}';
3638 if (ENABLE_HUSH_BASH_COMPAT
3639 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003640 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003641 ) {
3642 /* It's ${var:N[:M]} thing */
3643 end_ch = '}' * 0x100 + ':';
3644 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003645 if (ENABLE_HUSH_BASH_COMPAT
3646 && ch == '/'
3647 ) {
3648 /* It's ${var/[/]pattern[/repl]} thing */
3649 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3650 i_getch(input);
3651 nommu_addchr(as_string, '/');
3652 ch = '\\';
3653 }
3654 end_ch = '}' * 0x100 + '/';
3655 }
3656 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003657 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003658 if (!BB_MMU)
3659 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003660#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003661 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003662#else
3663#error Simple code to only allow ${var} is not implemented
3664#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003665 if (as_string) {
3666 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003667 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003668 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003669
3670 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3671 /* close the first block: */
3672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003673 /* while parsing N from ${var:N[:M]}
3674 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003675 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003676 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003677 end_ch = '}';
3678 goto again;
3679 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003680 /* got '}' */
3681 if (end_ch == '}' * 0x100 + ':') {
3682 /* it's ${var:N} - emulate :999999999 */
3683 o_addstr(dest, "999999999");
3684 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003685 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003686 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003687 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003688 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003689 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3690 break;
3691 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003692#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003693 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003694 unsigned pos;
3695
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003696 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003697 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003698# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003699 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003700 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003701 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003702 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3703 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003704 if (!BB_MMU)
3705 pos = dest->length;
3706 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003707 if (as_string) {
3708 o_addstr(as_string, dest->data + pos);
3709 o_addchr(as_string, ')');
3710 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003711 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003712 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003713 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003714 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003715# endif
3716# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003717 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3718 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003719 if (!BB_MMU)
3720 pos = dest->length;
3721 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003722 if (as_string) {
3723 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003724 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003725 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003727# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003728 break;
3729 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003730#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003731 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003732 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003733 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003734 ch = i_peek(input);
3735 if (isalnum(ch)) { /* it's $_name or $_123 */
3736 ch = '_';
3737 goto make_var;
3738 }
3739 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003740 /* TODO: $_ and $-: */
3741 /* $_ Shell or shell script name; or last argument of last command
3742 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3743 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003744 /* $- Option flags set by set builtin or shell options (-i etc) */
3745 default:
3746 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003747 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003748 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003749 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003750#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003751}
3752
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003753#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003754# if ENABLE_HUSH_BASH_COMPAT
3755#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3756 encode_string(dest, input, dquote_end, process_bkslash)
3757# else
3758/* only ${var/pattern/repl} (its pattern part) needs additional mode */
3759#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3760 encode_string(dest, input, dquote_end)
3761# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003762#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003763
3764#else /* !MMU */
3765
3766# if ENABLE_HUSH_BASH_COMPAT
3767/* all parameters are needed, no macro tricks */
3768# else
3769#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3770 encode_string(as_string, dest, input, dquote_end)
3771# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003772#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003773static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003774 o_string *dest,
3775 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02003776 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003777 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003778{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003779#if !ENABLE_HUSH_BASH_COMPAT
3780 const int process_bkslash = 1;
3781#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003782 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003783 int next;
3784
3785 again:
3786 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003787 if (ch != EOF)
3788 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003789 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003790 debug_printf_parse("encode_string return 0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003791 return 0;
3792 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003793 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003794 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003795 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003796 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003797 }
3798 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003799 if (ch != '\n') {
3800 next = i_peek(input);
3801 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003802 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003803 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003804 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003805 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003806 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003807 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003808 }
3809 /* bash:
3810 * "The backslash retains its special meaning [in "..."]
3811 * only when followed by one of the following characters:
3812 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003813 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003814 * NB: in (unquoted) heredoc, above does not apply to ",
3815 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003816 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003817 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003818 ch = i_getch(input); /* eat next */
3819 if (ch == '\n')
3820 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02003821 } /* else: ch remains == '\\', and we double it below: */
3822 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003823 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003824 goto again;
3825 }
3826 if (ch == '$') {
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003827 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003828 debug_printf_parse("encode_string return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003829 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003830 return 1;
3831 }
3832 goto again;
3833 }
3834#if ENABLE_HUSH_TICK
3835 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003836 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003837 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3838 o_addchr(dest, 0x80 | '`');
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003839 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003840 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3841 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003842 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003843 }
3844#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003845 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003846 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003847#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003848}
3849
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003850/*
3851 * Scan input until EOF or end_trigger char.
3852 * Return a list of pipes to execute, or NULL on EOF
3853 * or if end_trigger character is met.
3854 * On syntax error, exit is shell is not interactive,
3855 * reset parsing machinery and start parsing anew,
3856 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003857 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003858static struct pipe *parse_stream(char **pstring,
3859 struct in_str *input,
3860 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003861{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003862 struct parse_context ctx;
3863 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003864 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00003865
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003866 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003867 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003868 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003869 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02003870 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003871 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003872
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003873 /* If very first arg is "" or '', dest.data may end up NULL.
3874 * Preventing this: */
3875 o_addchr(&dest, '\0');
3876 dest.length = 0;
3877
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003878 /* We used to separate words on $IFS here. This was wrong.
3879 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003880 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003881 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003882
3883 reset: /* we come back here only on syntax errors in interactive shell */
3884
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003885#if ENABLE_HUSH_INTERACTIVE
3886 input->promptmode = 0; /* PS1 */
3887#endif
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003888 if (MAYBE_ASSIGNMENT != 0)
3889 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003890 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003891 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003892 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003893 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003894 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003895 int ch;
3896 int next;
3897 int redir_fd;
3898 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003899
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003900 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003901 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003902 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003903 if (ch == EOF) {
3904 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003905
3906 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003907 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003908 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003909 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003910 /* end_trigger == '}' case errors out earlier,
3911 * checking only ')' */
3912 if (end_trigger == ')') {
3913 syntax_error_unterm_ch('('); /* exits */
3914 /* goto parse_error; */
3915 }
3916
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003917 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003918 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003919 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003920 o_free(&dest);
3921 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003922 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003923 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003924 /* (this makes bare "&" cmd a no-op.
3925 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003926 if (pi->num_cmds == 0
3927 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3928 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003929 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003930 pi = NULL;
3931 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003932#if !BB_MMU
3933 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3934 if (pstring)
3935 *pstring = ctx.as_string.data;
3936 else
3937 o_free_unsafe(&ctx.as_string);
3938#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003939 debug_leave();
3940 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003941 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003942 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003943 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003944
3945 next = '\0';
3946 if (ch != '\n')
3947 next = i_peek(input);
3948
3949 is_special = "{}<>;&|()#'" /* special outside of "str" */
3950 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3951 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003952 if (ctx.command->argv /* word [word]{... - non-special */
3953 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003954 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003955 || (next != ';' /* }; - special */
3956 && next != ')' /* }) - special */
3957 && next != '&' /* }& and }&& ... - special */
3958 && next != '|' /* }|| ... - special */
3959 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003960 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003961 ) {
3962 /* They are not special, skip "{}" */
3963 is_special += 2;
3964 }
3965 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003966 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003967
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003968 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003969 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003970 o_addQchr(&dest, ch);
3971 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3972 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003973 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003974 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00003975 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003976 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003977 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003978 continue;
3979 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00003980
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003981 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003982 if (done_word(&dest, &ctx)) {
3983 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00003984 }
Denis Vlasenko37181682009-04-03 03:19:15 +00003985 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003986#if ENABLE_HUSH_CASE
3987 /* "case ... in <newline> word) ..." -
3988 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003989 if (ctx.command->argv == NULL
3990 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00003991 ) {
3992 continue;
3993 }
3994#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003995 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003996 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003997 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3998 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003999 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004000 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004001 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004002 heredoc_cnt = 0;
4003 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004004 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004005 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004006 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004007 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004008 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004009 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004010
4011 /* "cmd}" or "cmd }..." without semicolon or &:
4012 * } is an ordinary char in this case, even inside { cmd; }
4013 * Pathological example: { ""}; } should exec "}" cmd
4014 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004015 if (ch == '}') {
4016 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4017 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004018 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004019 ) {
4020 goto ordinary_char;
4021 }
4022 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4023 goto skip_end_trigger;
4024 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004025 }
4026
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004027 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004028 && (ch != ';' || heredoc_cnt == 0)
4029#if ENABLE_HUSH_CASE
4030 && (ch != ')'
4031 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004032 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004033 )
4034#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004035 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004036 if (heredoc_cnt) {
4037 /* This is technically valid:
4038 * { cat <<HERE; }; echo Ok
4039 * heredoc
4040 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004041 * HERE
4042 * but we don't support this.
4043 * We require heredoc to be in enclosing {}/(),
4044 * if any.
4045 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004046 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004047 goto parse_error;
4048 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004049 if (done_word(&dest, &ctx)) {
4050 goto parse_error;
4051 }
4052 done_pipe(&ctx, PIPE_SEQ);
4053 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004054 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004055 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004056 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004057 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004058 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004059#if !BB_MMU
4060 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4061 if (pstring)
4062 *pstring = ctx.as_string.data;
4063 else
4064 o_free_unsafe(&ctx.as_string);
4065#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004066 debug_leave();
4067 debug_printf_parse("parse_stream return %p: "
4068 "end_trigger char found\n",
4069 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004070 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004071 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004072 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004073 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004074 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004075 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004076
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004077 /* Catch <, > before deciding whether this word is
4078 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4079 switch (ch) {
4080 case '>':
4081 redir_fd = redirect_opt_num(&dest);
4082 if (done_word(&dest, &ctx)) {
4083 goto parse_error;
4084 }
4085 redir_style = REDIRECT_OVERWRITE;
4086 if (next == '>') {
4087 redir_style = REDIRECT_APPEND;
4088 ch = i_getch(input);
4089 nommu_addchr(&ctx.as_string, ch);
4090 }
4091#if 0
4092 else if (next == '(') {
4093 syntax_error(">(process) not supported");
4094 goto parse_error;
4095 }
4096#endif
4097 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4098 goto parse_error;
4099 continue; /* back to top of while (1) */
4100 case '<':
4101 redir_fd = redirect_opt_num(&dest);
4102 if (done_word(&dest, &ctx)) {
4103 goto parse_error;
4104 }
4105 redir_style = REDIRECT_INPUT;
4106 if (next == '<') {
4107 redir_style = REDIRECT_HEREDOC;
4108 heredoc_cnt++;
4109 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4110 ch = i_getch(input);
4111 nommu_addchr(&ctx.as_string, ch);
4112 } else if (next == '>') {
4113 redir_style = REDIRECT_IO;
4114 ch = i_getch(input);
4115 nommu_addchr(&ctx.as_string, ch);
4116 }
4117#if 0
4118 else if (next == '(') {
4119 syntax_error("<(process) not supported");
4120 goto parse_error;
4121 }
4122#endif
4123 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4124 goto parse_error;
4125 continue; /* back to top of while (1) */
4126 }
4127
4128 if (dest.o_assignment == MAYBE_ASSIGNMENT
4129 /* check that we are not in word in "a=1 2>word b=1": */
4130 && !ctx.pending_redirect
4131 ) {
4132 /* ch is a special char and thus this word
4133 * cannot be an assignment */
4134 dest.o_assignment = NOT_ASSIGNMENT;
4135 }
4136
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004137 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4138
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004139 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00004140 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004141 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004142 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004143 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004144 if (ch == EOF || ch == '\n')
4145 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004146 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004147 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004148 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004149 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00004150 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004151 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004152 }
4153 break;
4154 case '\\':
4155 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004156 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004157 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004158 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004159 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004160 if (ch != '\n') {
4161 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004162 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004163 o_addchr(&dest, ch);
4164 nommu_addchr(&ctx.as_string, ch);
4165 /* Example: echo Hello \2>file
4166 * we need to know that word 2 is quoted */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004167 dest.has_quoted_part = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004168 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004169#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004170 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004171 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4172 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004173 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02004174#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004175 break;
4176 case '$':
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004177 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004178 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004179 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004180 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004181 }
Eric Andersen25f27032001-04-26 23:22:31 +00004182 break;
4183 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004184 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004185 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004186 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004187 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004188 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004189 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004190 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004191 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004192 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004193 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004194 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004195 }
Eric Andersen25f27032001-04-26 23:22:31 +00004196 break;
4197 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004198 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004199 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004200 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004201 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004202 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004203 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004204 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004205#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004206 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004207 unsigned pos;
4208
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004209 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4210 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004211 pos = dest.length;
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004212 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004213# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004214 o_addstr(&ctx.as_string, dest.data + pos);
4215 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004216# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004217 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4218 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004219 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004220 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004221#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004222 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004223#if ENABLE_HUSH_CASE
4224 case_semi:
4225#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004226 if (done_word(&dest, &ctx)) {
4227 goto parse_error;
4228 }
4229 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004230#if ENABLE_HUSH_CASE
4231 /* Eat multiple semicolons, detect
4232 * whether it means something special */
4233 while (1) {
4234 ch = i_peek(input);
4235 if (ch != ';')
4236 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004237 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004238 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004239 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004240 ctx.ctx_dsemicolon = 1;
4241 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004242 break;
4243 }
4244 }
4245#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004246 new_cmd:
4247 /* We just finished a cmd. New one may start
4248 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004249 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004250 break;
4251 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004252 if (done_word(&dest, &ctx)) {
4253 goto parse_error;
4254 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004255 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004256 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004257 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004258 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004259 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004260 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004261 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004262 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004263 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004264 if (done_word(&dest, &ctx)) {
4265 goto parse_error;
4266 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004267#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004268 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004269 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004270#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004271 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004272 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004273 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004274 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004275 } else {
4276 /* we could pick up a file descriptor choice here
4277 * with redirect_opt_num(), but bash doesn't do it.
4278 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004279 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004280#if !BB_MMU
4281 o_reset_to_empty_unquoted(&ctx.as_string);
4282#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004283 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004284 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004285 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004286#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004287 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004288 if (ctx.ctx_res_w == RES_MATCH
4289 && ctx.command->argv == NULL /* not (word|(... */
4290 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004291 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004292 ) {
4293 continue;
4294 }
4295#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004296 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004297 if (parse_group(&dest, &ctx, input, ch) != 0) {
4298 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004299 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004300 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004301 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004302#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004303 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004304 goto case_semi;
4305#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004306 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004307 /* proper use of this character is caught by end_trigger:
4308 * if we see {, we call parse_group(..., end_trigger='}')
4309 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004310 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004311 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004312 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004313 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004314 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004315 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004316 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004317
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004318 parse_error:
4319 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004320 struct parse_context *pctx;
4321 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004322
4323 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004324 * Sample for finding leaks on syntax error recovery path.
4325 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004326 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004327 * Samples to catch leaks at execution:
4328 * while if (true | {true;}); then echo ok; fi; do break; done
4329 * 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 +00004330 */
4331 pctx = &ctx;
4332 do {
4333 /* Update pipe/command counts,
4334 * otherwise freeing may miss some */
4335 done_pipe(pctx, PIPE_SEQ);
4336 debug_printf_clean("freeing list %p from ctx %p\n",
4337 pctx->list_head, pctx);
4338 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004339 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004340 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004341#if !BB_MMU
4342 o_free_unsafe(&pctx->as_string);
4343#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004344 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004345 if (pctx != &ctx) {
4346 free(pctx);
4347 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004348 IF_HAS_KEYWORDS(pctx = p2;)
4349 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004350 /* Free text, clear all dest fields */
4351 o_free(&dest);
4352 /* If we are not in top-level parse, we return,
4353 * our caller will propagate error.
4354 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004355 if (end_trigger != ';') {
4356#if !BB_MMU
4357 if (pstring)
4358 *pstring = NULL;
4359#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004360 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004361 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004362 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004363 /* Discard cached input, force prompt */
4364 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004365 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004366 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004367 }
Eric Andersen25f27032001-04-26 23:22:31 +00004368}
4369
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004370
4371/*** Execution routines ***/
4372
4373/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004374#if !ENABLE_HUSH_BASH_COMPAT
4375/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4376#define expand_string_to_string(str, do_unbackslash) \
4377 expand_string_to_string(str)
4378#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004379static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004380static int process_command_subs(o_string *dest, const char *s);
4381
4382/* expand_strvec_to_strvec() takes a list of strings, expands
4383 * all variable references within and returns a pointer to
4384 * a list of expanded strings, possibly with larger number
4385 * of strings. (Think VAR="a b"; echo $VAR).
4386 * This new list is allocated as a single malloc block.
4387 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004388 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004389 * Caller can deallocate entire list by single free(list). */
4390
4391/* Store given string, finalizing the word and starting new one whenever
4392 * we encounter IFS char(s). This is used for expanding variable values.
4393 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4394static int expand_on_ifs(o_string *output, int n, const char *str)
4395{
4396 while (1) {
4397 int word_len = strcspn(str, G.ifs);
4398 if (word_len) {
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004399 if (!(output->o_expflags & EXP_FLAG_GLOB))
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004400 o_addblock(output, str, word_len);
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004401 else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004402 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004403 * Example: "v='\*'; echo b$v" prints "b\*"
4404 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004405 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004406 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004407 /*/ Why can't we do it easier? */
4408 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4409 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4410 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004411 str += word_len;
4412 }
4413 if (!*str) /* EOL - do not finalize word */
4414 break;
4415 o_addchr(output, '\0');
4416 debug_print_list("expand_on_ifs", output, n);
4417 n = o_save_ptr(output, n);
4418 str += strspn(str, G.ifs); /* skip ifs chars */
4419 }
4420 debug_print_list("expand_on_ifs[1]", output, n);
4421 return n;
4422}
4423
4424/* Helper to expand $((...)) and heredoc body. These act as if
4425 * they are in double quotes, with the exception that they are not :).
4426 * Just the rules are similar: "expand only $var and `cmd`"
4427 *
4428 * Returns malloced string.
4429 * As an optimization, we return NULL if expansion is not needed.
4430 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004431#if !ENABLE_HUSH_BASH_COMPAT
4432/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4433#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4434 encode_then_expand_string(str)
4435#endif
4436static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004437{
4438 char *exp_str;
4439 struct in_str input;
4440 o_string dest = NULL_O_STRING;
4441
4442 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004443 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004444#if ENABLE_HUSH_TICK
4445 && !strchr(str, '`')
4446#endif
4447 ) {
4448 return NULL;
4449 }
4450
4451 /* We need to expand. Example:
4452 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4453 */
4454 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004455 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004456 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004457 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004458 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4459 o_free_unsafe(&dest);
4460 return exp_str;
4461}
4462
4463#if ENABLE_SH_MATH_SUPPORT
4464static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
4465{
4466 arith_eval_hooks_t hooks;
4467 arith_t res;
4468 char *exp_str;
4469
4470 hooks.lookupvar = get_local_var_value;
4471 hooks.setvar = set_local_var_from_halves;
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02004472 //hooks.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004473 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004474 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
4475 free(exp_str);
4476 return res;
4477}
4478#endif
4479
4480#if ENABLE_HUSH_BASH_COMPAT
4481/* ${var/[/]pattern[/repl]} helpers */
4482static char *strstr_pattern(char *val, const char *pattern, int *size)
4483{
4484 while (1) {
4485 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4486 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4487 if (end) {
4488 *size = end - val;
4489 return val;
4490 }
4491 if (*val == '\0')
4492 return NULL;
4493 /* Optimization: if "*pat" did not match the start of "string",
4494 * we know that "tring", "ring" etc will not match too:
4495 */
4496 if (pattern[0] == '*')
4497 return NULL;
4498 val++;
4499 }
4500}
4501static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4502{
4503 char *result = NULL;
4504 unsigned res_len = 0;
4505 unsigned repl_len = strlen(repl);
4506
4507 while (1) {
4508 int size;
4509 char *s = strstr_pattern(val, pattern, &size);
4510 if (!s)
4511 break;
4512
4513 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4514 memcpy(result + res_len, val, s - val);
4515 res_len += s - val;
4516 strcpy(result + res_len, repl);
4517 res_len += repl_len;
4518 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4519
4520 val = s + size;
4521 if (exp_op == '/')
4522 break;
4523 }
4524 if (val[0] && result) {
4525 result = xrealloc(result, res_len + strlen(val) + 1);
4526 strcpy(result + res_len, val);
4527 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4528 }
4529 debug_printf_varexp("result:'%s'\n", result);
4530 return result;
4531}
4532#endif
4533
4534/* Helper:
4535 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4536 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004537static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004538{
4539 const char *val = NULL;
4540 char *to_be_freed = NULL;
4541 char *p = *pp;
4542 char *var;
4543 char first_char;
4544 char exp_op;
4545 char exp_save = exp_save; /* for compiler */
4546 char *exp_saveptr; /* points to expansion operator */
4547 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004548 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004549
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004550 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004551 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004552 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004553 arg0 = arg[0];
4554 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004555 exp_op = 0;
4556
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004557 if (first_char == '#' /* ${#... */
4558 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4559 ) {
4560 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004561 var++;
4562 exp_op = 'L';
4563 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004564 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004565 if (exp_saveptr /* if 2nd char is one of expansion operators */
4566 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4567 ) {
4568 /* ${?:0}, ${#[:]%0} etc */
4569 exp_saveptr = var + 1;
4570 } else {
4571 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4572 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4573 }
4574 exp_op = exp_save = *exp_saveptr;
4575 if (exp_op) {
4576 exp_word = exp_saveptr + 1;
4577 if (exp_op == ':') {
4578 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004579//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004580 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004581 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004582 ) {
4583 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4584 exp_op = ':';
4585 exp_word--;
4586 }
4587 }
4588 *exp_saveptr = '\0';
4589 } /* else: it's not an expansion op, but bare ${var} */
4590 }
4591
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004592 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004593 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004594 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004595 int n = xatoi_positive(var);
4596 if (n < G.global_argc)
4597 val = G.global_argv[n];
4598 /* else val remains NULL: $N with too big N */
4599 } else {
4600 switch (var[0]) {
4601 case '$': /* pid */
4602 val = utoa(G.root_pid);
4603 break;
4604 case '!': /* bg pid */
4605 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4606 break;
4607 case '?': /* exitcode */
4608 val = utoa(G.last_exitcode);
4609 break;
4610 case '#': /* argc */
4611 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4612 break;
4613 default:
4614 val = get_local_var_value(var);
4615 }
4616 }
4617
4618 /* Handle any expansions */
4619 if (exp_op == 'L') {
4620 debug_printf_expand("expand: length(%s)=", val);
4621 val = utoa(val ? strlen(val) : 0);
4622 debug_printf_expand("%s\n", val);
4623 } else if (exp_op) {
4624 if (exp_op == '%' || exp_op == '#') {
4625 /* Standard-mandated substring removal ops:
4626 * ${parameter%word} - remove smallest suffix pattern
4627 * ${parameter%%word} - remove largest suffix pattern
4628 * ${parameter#word} - remove smallest prefix pattern
4629 * ${parameter##word} - remove largest prefix pattern
4630 *
4631 * Word is expanded to produce a glob pattern.
4632 * Then var's value is matched to it and matching part removed.
4633 */
4634 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004635 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004636 char *exp_exp_word;
4637 char *loc;
4638 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4639 if (exp_op == *exp_word) /* ## or %% */
4640 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004641 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004642 if (exp_exp_word)
4643 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004644 /* HACK ALERT. We depend here on the fact that
4645 * G.global_argv and results of utoa and get_local_var_value
4646 * are actually in writable memory:
4647 * scan_and_match momentarily stores NULs there. */
4648 t = (char*)val;
4649 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004650 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004651 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004652 free(exp_exp_word);
4653 if (loc) { /* match was found */
4654 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004655 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004656 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004657 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004658 }
4659 }
4660 }
4661#if ENABLE_HUSH_BASH_COMPAT
4662 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004663 /* It's ${var/[/]pattern[/repl]} thing.
4664 * Note that in encoded form it has TWO parts:
4665 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02004666 * and if // is used, it is encoded as \:
4667 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004668 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004669 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004670 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004671 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004672 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004673 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004674 * by the usual expansion rules:
4675 * >az; >bz;
4676 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4677 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4678 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4679 * v='a bz'; echo ${v/a*z/\z} prints "z"
4680 * (note that a*z _pattern_ is never globbed!)
4681 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004682 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004683 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004684 if (!pattern)
4685 pattern = xstrdup(exp_word);
4686 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4687 *p++ = SPECIAL_VAR_SYMBOL;
4688 exp_word = p;
4689 p = strchr(p, SPECIAL_VAR_SYMBOL);
4690 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004691 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004692 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4693 /* HACK ALERT. We depend here on the fact that
4694 * G.global_argv and results of utoa and get_local_var_value
4695 * are actually in writable memory:
4696 * replace_pattern momentarily stores NULs there. */
4697 t = (char*)val;
4698 to_be_freed = replace_pattern(t,
4699 pattern,
4700 (repl ? repl : exp_word),
4701 exp_op);
4702 if (to_be_freed) /* at least one replace happened */
4703 val = to_be_freed;
4704 free(pattern);
4705 free(repl);
4706 }
4707 }
4708#endif
4709 else if (exp_op == ':') {
4710#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4711 /* It's ${var:N[:M]} bashism.
4712 * Note that in encoded form it has TWO parts:
4713 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4714 */
4715 arith_t beg, len;
4716 int errcode = 0;
4717
4718 beg = expand_and_evaluate_arith(exp_word, &errcode);
4719 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4720 *p++ = SPECIAL_VAR_SYMBOL;
4721 exp_word = p;
4722 p = strchr(p, SPECIAL_VAR_SYMBOL);
4723 *p = '\0';
4724 len = expand_and_evaluate_arith(exp_word, &errcode);
4725 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4726
4727 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
4728 if (beg < 0) /* bash compat */
4729 beg = 0;
4730 debug_printf_varexp("from val:'%s'\n", val);
4731 if (len == 0 || !val || beg >= strlen(val))
4732 val = "";
4733 else {
4734 /* Paranoia. What if user entered 9999999999999
4735 * which fits in arith_t but not int? */
4736 if (len >= INT_MAX)
4737 len = INT_MAX;
4738 val = to_be_freed = xstrndup(val + beg, len);
4739 }
4740 debug_printf_varexp("val:'%s'\n", val);
4741 } else
4742#endif
4743 {
4744 die_if_script("malformed ${%s:...}", var);
4745 val = "";
4746 }
4747 } else { /* one of "-=+?" */
4748 /* Standard-mandated substitution ops:
4749 * ${var?word} - indicate error if unset
4750 * If var is unset, word (or a message indicating it is unset
4751 * if word is null) is written to standard error
4752 * and the shell exits with a non-zero exit status.
4753 * Otherwise, the value of var is substituted.
4754 * ${var-word} - use default value
4755 * If var is unset, word is substituted.
4756 * ${var=word} - assign and use default value
4757 * If var is unset, word is assigned to var.
4758 * In all cases, final value of var is substituted.
4759 * ${var+word} - use alternative value
4760 * If var is unset, null is substituted.
4761 * Otherwise, word is substituted.
4762 *
4763 * Word is subjected to tilde expansion, parameter expansion,
4764 * command substitution, and arithmetic expansion.
4765 * If word is not needed, it is not expanded.
4766 *
4767 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4768 * but also treat null var as if it is unset.
4769 */
4770 int use_word = (!val || ((exp_save == ':') && !val[0]));
4771 if (exp_op == '+')
4772 use_word = !use_word;
4773 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4774 (exp_save == ':') ? "true" : "false", use_word);
4775 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004776 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004777 if (to_be_freed)
4778 exp_word = to_be_freed;
4779 if (exp_op == '?') {
4780 /* mimic bash message */
4781 die_if_script("%s: %s",
4782 var,
4783 exp_word[0] ? exp_word : "parameter null or not set"
4784 );
4785//TODO: how interactive bash aborts expansion mid-command?
4786 } else {
4787 val = exp_word;
4788 }
4789
4790 if (exp_op == '=') {
4791 /* ${var=[word]} or ${var:=[word]} */
4792 if (isdigit(var[0]) || var[0] == '#') {
4793 /* mimic bash message */
4794 die_if_script("$%s: cannot assign in this way", var);
4795 val = NULL;
4796 } else {
4797 char *new_var = xasprintf("%s=%s", var, val);
4798 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4799 }
4800 }
4801 }
4802 } /* one of "-=+?" */
4803
4804 *exp_saveptr = exp_save;
4805 } /* if (exp_op) */
4806
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004807 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004808
4809 *pp = p;
4810 *to_be_freed_pp = to_be_freed;
4811 return val;
4812}
4813
4814/* Expand all variable references in given string, adding words to list[]
4815 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4816 * to be filled). This routine is extremely tricky: has to deal with
4817 * variables/parameters with whitespace, $* and $@, and constructs like
4818 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004819static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004820{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004821 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004822 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004823 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004824 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004825 char *p;
4826
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004827 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4828 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004829 debug_print_list("expand_vars_to_list", output, n);
4830 n = o_save_ptr(output, n);
4831 debug_print_list("expand_vars_to_list[0]", output, n);
4832
4833 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4834 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004835 char *to_be_freed = NULL;
4836 const char *val = NULL;
4837#if ENABLE_HUSH_TICK
4838 o_string subst_result = NULL_O_STRING;
4839#endif
4840#if ENABLE_SH_MATH_SUPPORT
4841 char arith_buf[sizeof(arith_t)*3 + 2];
4842#endif
4843 o_addblock(output, arg, p - arg);
4844 debug_print_list("expand_vars_to_list[1]", output, n);
4845 arg = ++p;
4846 p = strchr(p, SPECIAL_VAR_SYMBOL);
4847
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004848 /* Fetch special var name (if it is indeed one of them)
4849 * and quote bit, force the bit on if singleword expansion -
4850 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004851 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004852
4853 /* Is this variable quoted and thus expansion can't be null?
4854 * "$@" is special. Even if quoted, it can still
4855 * expand to nothing (not even an empty string),
4856 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004857 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004858 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004859
4860 switch (first_ch & 0x7f) {
4861 /* Highest bit in first_ch indicates that var is double-quoted */
4862 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004863 case '@': {
4864 int i;
4865 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004866 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004867 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004868 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004869 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004870 while (G.global_argv[i]) {
4871 n = expand_on_ifs(output, n, G.global_argv[i]);
4872 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4873 if (G.global_argv[i++][0] && G.global_argv[i]) {
4874 /* this argv[] is not empty and not last:
4875 * put terminating NUL, start new word */
4876 o_addchr(output, '\0');
4877 debug_print_list("expand_vars_to_list[2]", output, n);
4878 n = o_save_ptr(output, n);
4879 debug_print_list("expand_vars_to_list[3]", output, n);
4880 }
4881 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004882 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004883 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004884 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004885 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004886 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004887 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004888 while (1) {
4889 o_addQstr(output, G.global_argv[i]);
4890 if (++i >= G.global_argc)
4891 break;
4892 o_addchr(output, '\0');
4893 debug_print_list("expand_vars_to_list[4]", output, n);
4894 n = o_save_ptr(output, n);
4895 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004896 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004897 while (1) {
4898 o_addQstr(output, G.global_argv[i]);
4899 if (!G.global_argv[++i])
4900 break;
4901 if (G.ifs[0])
4902 o_addchr(output, G.ifs[0]);
4903 }
4904 }
4905 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004906 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004907 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4908 /* "Empty variable", used to make "" etc to not disappear */
4909 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004910 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004911 break;
4912#if ENABLE_HUSH_TICK
4913 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004914 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004915 arg++;
4916 /* Can't just stuff it into output o_string,
4917 * expanded result may need to be globbed
4918 * and $IFS-splitted */
4919 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4920 G.last_exitcode = process_command_subs(&subst_result, arg);
4921 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4922 val = subst_result.data;
4923 goto store_val;
4924#endif
4925#if ENABLE_SH_MATH_SUPPORT
4926 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4927 arith_t res;
4928 int errcode;
4929
4930 arg++; /* skip '+' */
4931 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4932 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4933 res = expand_and_evaluate_arith(arg, &errcode);
4934
4935 if (errcode < 0) {
4936 const char *msg = "error in arithmetic";
4937 switch (errcode) {
4938 case -3:
4939 msg = "exponent less than 0";
4940 break;
4941 case -2:
4942 msg = "divide by 0";
4943 break;
4944 case -5:
4945 msg = "expression recursion loop detected";
4946 break;
4947 }
4948 die_if_script(msg);
4949 }
4950 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
4951 sprintf(arith_buf, arith_t_fmt, res);
4952 val = arith_buf;
4953 break;
4954 }
4955#endif
4956 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004957 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004958 IF_HUSH_TICK(store_val:)
4959 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004960 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
4961 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004962 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004963 n = expand_on_ifs(output, n, val);
4964 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004965 }
4966 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004967 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
4968 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004969 }
4970 break;
4971
4972 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4973
4974 if (val && val[0]) {
4975 o_addQstr(output, val);
4976 }
4977 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004978
4979 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
4980 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004981 if (*p != SPECIAL_VAR_SYMBOL)
4982 *p = SPECIAL_VAR_SYMBOL;
4983
4984#if ENABLE_HUSH_TICK
4985 o_free(&subst_result);
4986#endif
4987 arg = ++p;
4988 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4989
4990 if (arg[0]) {
4991 debug_print_list("expand_vars_to_list[a]", output, n);
4992 /* this part is literal, and it was already pre-quoted
4993 * if needed (much earlier), do not use o_addQstr here! */
4994 o_addstr_with_NUL(output, arg);
4995 debug_print_list("expand_vars_to_list[b]", output, n);
4996 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004997 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004998 ) {
4999 n--;
5000 /* allow to reuse list[n] later without re-growth */
5001 output->has_empty_slot = 1;
5002 } else {
5003 o_addchr(output, '\0');
5004 }
5005
5006 return n;
5007}
5008
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005009static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005010{
5011 int n;
5012 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005013 o_string output = NULL_O_STRING;
5014
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005015 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005016
5017 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005018 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005019 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005020 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005021 }
5022 debug_print_list("expand_variables", &output, n);
5023
5024 /* output.data (malloced in one block) gets returned in "list" */
5025 list = o_finalize_list(&output, n);
5026 debug_print_strings("expand_variables[1]", list);
5027 return list;
5028}
5029
5030static char **expand_strvec_to_strvec(char **argv)
5031{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005032 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005033}
5034
5035#if ENABLE_HUSH_BASH_COMPAT
5036static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5037{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005038 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005039}
5040#endif
5041
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005042/* Used for expansion of right hand of assignments,
5043 * $((...)), heredocs, variable espansion parts.
5044 *
5045 * NB: should NOT do globbing!
5046 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5047 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005048static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005049{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005050#if !ENABLE_HUSH_BASH_COMPAT
5051 const int do_unbackslash = 1;
5052#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005053 char *argv[2], **list;
5054
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005055 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005056 /* This is generally an optimization, but it also
5057 * handles "", which otherwise trips over !list[0] check below.
5058 * (is this ever happens that we actually get str="" here?)
5059 */
5060 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5061 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005062 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005063 return xstrdup(str);
5064 }
5065
5066 argv[0] = (char*)str;
5067 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005068 list = expand_variables(argv, do_unbackslash
5069 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5070 : EXP_FLAG_SINGLEWORD
5071 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005072 if (HUSH_DEBUG)
5073 if (!list[0] || list[1])
5074 bb_error_msg_and_die("BUG in varexp2");
5075 /* actually, just move string 2*sizeof(char*) bytes back */
5076 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005077 if (do_unbackslash)
5078 unbackslash((char*)list);
5079 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005080 return (char*)list;
5081}
5082
5083/* Used for "eval" builtin */
5084static char* expand_strvec_to_string(char **argv)
5085{
5086 char **list;
5087
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005088 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005089 /* Convert all NULs to spaces */
5090 if (list[0]) {
5091 int n = 1;
5092 while (list[n]) {
5093 if (HUSH_DEBUG)
5094 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5095 bb_error_msg_and_die("BUG in varexp3");
5096 /* bash uses ' ' regardless of $IFS contents */
5097 list[n][-1] = ' ';
5098 n++;
5099 }
5100 }
5101 overlapping_strcpy((char*)list, list[0]);
5102 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5103 return (char*)list;
5104}
5105
5106static char **expand_assignments(char **argv, int count)
5107{
5108 int i;
5109 char **p;
5110
5111 G.expanded_assignments = p = NULL;
5112 /* Expand assignments into one string each */
5113 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005114 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005115 }
5116 G.expanded_assignments = NULL;
5117 return p;
5118}
5119
5120
5121#if BB_MMU
5122/* never called */
5123void re_execute_shell(char ***to_free, const char *s,
5124 char *g_argv0, char **g_argv,
5125 char **builtin_argv) NORETURN;
5126
5127static void reset_traps_to_defaults(void)
5128{
5129 /* This function is always called in a child shell
5130 * after fork (not vfork, NOMMU doesn't use this function).
5131 */
5132 unsigned sig;
5133 unsigned mask;
5134
5135 /* Child shells are not interactive.
5136 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5137 * Testcase: (while :; do :; done) + ^Z should background.
5138 * Same goes for SIGTERM, SIGHUP, SIGINT.
5139 */
5140 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5141 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5142
5143 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5144 * Stupid. It can be done with *single* &= op, but we can't use
5145 * the fact that G.blocked_set is implemented as a bitmask
5146 * in libc... */
5147 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5148 sig = 1;
5149 while (1) {
5150 if (mask & 1) {
5151 /* Careful. Only if no trap or trap is not "" */
5152 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5153 sigdelset(&G.blocked_set, sig);
5154 }
5155 mask >>= 1;
5156 if (!mask)
5157 break;
5158 sig++;
5159 }
5160 /* Our homegrown sig mask is saner to work with :) */
5161 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5162
5163 /* Resetting all traps to default except empty ones */
5164 mask = G.non_DFL_mask;
5165 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5166 if (!G.traps[sig] || !G.traps[sig][0])
5167 continue;
5168 free(G.traps[sig]);
5169 G.traps[sig] = NULL;
5170 /* There is no signal for 0 (EXIT) */
5171 if (sig == 0)
5172 continue;
5173 /* There was a trap handler, we just removed it.
5174 * But if sig still has non-DFL handling,
5175 * we should not unblock the sig. */
5176 if (mask & 1)
5177 continue;
5178 sigdelset(&G.blocked_set, sig);
5179 }
5180 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5181}
5182
5183#else /* !BB_MMU */
5184
5185static void re_execute_shell(char ***to_free, const char *s,
5186 char *g_argv0, char **g_argv,
5187 char **builtin_argv) NORETURN;
5188static void re_execute_shell(char ***to_free, const char *s,
5189 char *g_argv0, char **g_argv,
5190 char **builtin_argv)
5191{
5192# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5193 /* delims + 2 * (number of bytes in printed hex numbers) */
5194 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5195 char *heredoc_argv[4];
5196 struct variable *cur;
5197# if ENABLE_HUSH_FUNCTIONS
5198 struct function *funcp;
5199# endif
5200 char **argv, **pp;
5201 unsigned cnt;
5202 unsigned long long empty_trap_mask;
5203
5204 if (!g_argv0) { /* heredoc */
5205 argv = heredoc_argv;
5206 argv[0] = (char *) G.argv0_for_re_execing;
5207 argv[1] = (char *) "-<";
5208 argv[2] = (char *) s;
5209 argv[3] = NULL;
5210 pp = &argv[3]; /* used as pointer to empty environment */
5211 goto do_exec;
5212 }
5213
5214 cnt = 0;
5215 pp = builtin_argv;
5216 if (pp) while (*pp++)
5217 cnt++;
5218
5219 empty_trap_mask = 0;
5220 if (G.traps) {
5221 int sig;
5222 for (sig = 1; sig < NSIG; sig++) {
5223 if (G.traps[sig] && !G.traps[sig][0])
5224 empty_trap_mask |= 1LL << sig;
5225 }
5226 }
5227
5228 sprintf(param_buf, NOMMU_HACK_FMT
5229 , (unsigned) G.root_pid
5230 , (unsigned) G.root_ppid
5231 , (unsigned) G.last_bg_pid
5232 , (unsigned) G.last_exitcode
5233 , cnt
5234 , empty_trap_mask
5235 IF_HUSH_LOOPS(, G.depth_of_loop)
5236 );
5237# undef NOMMU_HACK_FMT
5238 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5239 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5240 */
5241 cnt += 6;
5242 for (cur = G.top_var; cur; cur = cur->next) {
5243 if (!cur->flg_export || cur->flg_read_only)
5244 cnt += 2;
5245 }
5246# if ENABLE_HUSH_FUNCTIONS
5247 for (funcp = G.top_func; funcp; funcp = funcp->next)
5248 cnt += 3;
5249# endif
5250 pp = g_argv;
5251 while (*pp++)
5252 cnt++;
5253 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5254 *pp++ = (char *) G.argv0_for_re_execing;
5255 *pp++ = param_buf;
5256 for (cur = G.top_var; cur; cur = cur->next) {
5257 if (strcmp(cur->varstr, hush_version_str) == 0)
5258 continue;
5259 if (cur->flg_read_only) {
5260 *pp++ = (char *) "-R";
5261 *pp++ = cur->varstr;
5262 } else if (!cur->flg_export) {
5263 *pp++ = (char *) "-V";
5264 *pp++ = cur->varstr;
5265 }
5266 }
5267# if ENABLE_HUSH_FUNCTIONS
5268 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5269 *pp++ = (char *) "-F";
5270 *pp++ = funcp->name;
5271 *pp++ = funcp->body_as_string;
5272 }
5273# endif
5274 /* We can pass activated traps here. Say, -Tnn:trap_string
5275 *
5276 * However, POSIX says that subshells reset signals with traps
5277 * to SIG_DFL.
5278 * I tested bash-3.2 and it not only does that with true subshells
5279 * of the form ( list ), but with any forked children shells.
5280 * I set trap "echo W" WINCH; and then tried:
5281 *
5282 * { echo 1; sleep 20; echo 2; } &
5283 * while true; do echo 1; sleep 20; echo 2; break; done &
5284 * true | { echo 1; sleep 20; echo 2; } | cat
5285 *
5286 * In all these cases sending SIGWINCH to the child shell
5287 * did not run the trap. If I add trap "echo V" WINCH;
5288 * _inside_ group (just before echo 1), it works.
5289 *
5290 * I conclude it means we don't need to pass active traps here.
5291 * Even if we would use signal handlers instead of signal masking
5292 * in order to implement trap handling,
5293 * exec syscall below resets signals to SIG_DFL for us.
5294 */
5295 *pp++ = (char *) "-c";
5296 *pp++ = (char *) s;
5297 if (builtin_argv) {
5298 while (*++builtin_argv)
5299 *pp++ = *builtin_argv;
5300 *pp++ = (char *) "";
5301 }
5302 *pp++ = g_argv0;
5303 while (*g_argv)
5304 *pp++ = *g_argv++;
5305 /* *pp = NULL; - is already there */
5306 pp = environ;
5307
5308 do_exec:
5309 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5310 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5311 execve(bb_busybox_exec_path, argv, pp);
5312 /* Fallback. Useful for init=/bin/hush usage etc */
5313 if (argv[0][0] == '/')
5314 execve(argv[0], argv, pp);
5315 xfunc_error_retval = 127;
5316 bb_error_msg_and_die("can't re-execute the shell");
5317}
5318#endif /* !BB_MMU */
5319
5320
5321static int run_and_free_list(struct pipe *pi);
5322
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005323/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005324 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5325 * end_trigger controls how often we stop parsing
5326 * NUL: parse all, execute, return
5327 * ';': parse till ';' or newline, execute, repeat till EOF
5328 */
5329static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005330{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005331 /* Why we need empty flag?
5332 * An obscure corner case "false; ``; echo $?":
5333 * empty command in `` should still set $? to 0.
5334 * But we can't just set $? to 0 at the start,
5335 * this breaks "false; echo `echo $?`" case.
5336 */
5337 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005338 while (1) {
5339 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005340
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005341 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005342 if (!pipe_list) { /* EOF */
5343 if (empty)
5344 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005345 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005346 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005347 debug_print_tree(pipe_list, 0);
5348 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5349 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005350 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005351 }
Eric Andersen25f27032001-04-26 23:22:31 +00005352}
5353
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005354static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005355{
5356 struct in_str input;
5357 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005358 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005359}
5360
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005361static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005362{
Eric Andersen25f27032001-04-26 23:22:31 +00005363 struct in_str input;
5364 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005365 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005366}
5367
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005368#if ENABLE_HUSH_TICK
5369static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5370{
5371 pid_t pid;
5372 int channel[2];
5373# if !BB_MMU
5374 char **to_free = NULL;
5375# endif
5376
5377 xpipe(channel);
5378 pid = BB_MMU ? xfork() : xvfork();
5379 if (pid == 0) { /* child */
5380 disable_restore_tty_pgrp_on_exit();
5381 /* Process substitution is not considered to be usual
5382 * 'command execution'.
5383 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5384 */
5385 bb_signals(0
5386 + (1 << SIGTSTP)
5387 + (1 << SIGTTIN)
5388 + (1 << SIGTTOU)
5389 , SIG_IGN);
5390 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5391 close(channel[0]); /* NB: close _first_, then move fd! */
5392 xmove_fd(channel[1], 1);
5393 /* Prevent it from trying to handle ctrl-z etc */
5394 IF_HUSH_JOB(G.run_list_level = 1;)
5395 /* Awful hack for `trap` or $(trap).
5396 *
5397 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5398 * contains an example where "trap" is executed in a subshell:
5399 *
5400 * save_traps=$(trap)
5401 * ...
5402 * eval "$save_traps"
5403 *
5404 * Standard does not say that "trap" in subshell shall print
5405 * parent shell's traps. It only says that its output
5406 * must have suitable form, but then, in the above example
5407 * (which is not supposed to be normative), it implies that.
5408 *
5409 * bash (and probably other shell) does implement it
5410 * (traps are reset to defaults, but "trap" still shows them),
5411 * but as a result, "trap" logic is hopelessly messed up:
5412 *
5413 * # trap
5414 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5415 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5416 * # true | trap <--- trap is in subshell - no output (ditto)
5417 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5418 * trap -- 'echo Ho' SIGWINCH
5419 * # echo `(trap)` <--- in subshell in subshell - output
5420 * trap -- 'echo Ho' SIGWINCH
5421 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5422 * trap -- 'echo Ho' SIGWINCH
5423 *
5424 * The rules when to forget and when to not forget traps
5425 * get really complex and nonsensical.
5426 *
5427 * Our solution: ONLY bare $(trap) or `trap` is special.
5428 */
5429 s = skip_whitespace(s);
5430 if (strncmp(s, "trap", 4) == 0
5431 && skip_whitespace(s + 4)[0] == '\0'
5432 ) {
5433 static const char *const argv[] = { NULL, NULL };
5434 builtin_trap((char**)argv);
5435 exit(0); /* not _exit() - we need to fflush */
5436 }
5437# if BB_MMU
5438 reset_traps_to_defaults();
5439 parse_and_run_string(s);
5440 _exit(G.last_exitcode);
5441# else
5442 /* We re-execute after vfork on NOMMU. This makes this script safe:
5443 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5444 * huge=`cat BIG` # was blocking here forever
5445 * echo OK
5446 */
5447 re_execute_shell(&to_free,
5448 s,
5449 G.global_argv[0],
5450 G.global_argv + 1,
5451 NULL);
5452# endif
5453 }
5454
5455 /* parent */
5456 *pid_p = pid;
5457# if ENABLE_HUSH_FAST
5458 G.count_SIGCHLD++;
5459//bb_error_msg("[%d] fork in generate_stream_from_string:"
5460// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5461// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5462# endif
5463 enable_restore_tty_pgrp_on_exit();
5464# if !BB_MMU
5465 free(to_free);
5466# endif
5467 close(channel[1]);
5468 close_on_exec_on(channel[0]);
5469 return xfdopen_for_read(channel[0]);
5470}
5471
5472/* Return code is exit status of the process that is run. */
5473static int process_command_subs(o_string *dest, const char *s)
5474{
5475 FILE *fp;
5476 struct in_str pipe_str;
5477 pid_t pid;
5478 int status, ch, eol_cnt;
5479
5480 fp = generate_stream_from_string(s, &pid);
5481
5482 /* Now send results of command back into original context */
5483 setup_file_in_str(&pipe_str, fp);
5484 eol_cnt = 0;
5485 while ((ch = i_getch(&pipe_str)) != EOF) {
5486 if (ch == '\n') {
5487 eol_cnt++;
5488 continue;
5489 }
5490 while (eol_cnt) {
5491 o_addchr(dest, '\n');
5492 eol_cnt--;
5493 }
5494 o_addQchr(dest, ch);
5495 }
5496
5497 debug_printf("done reading from `cmd` pipe, closing it\n");
5498 fclose(fp);
5499 /* We need to extract exitcode. Test case
5500 * "true; echo `sleep 1; false` $?"
5501 * should print 1 */
5502 safe_waitpid(pid, &status, 0);
5503 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5504 return WEXITSTATUS(status);
5505}
5506#endif /* ENABLE_HUSH_TICK */
5507
5508
5509static void setup_heredoc(struct redir_struct *redir)
5510{
5511 struct fd_pair pair;
5512 pid_t pid;
5513 int len, written;
5514 /* the _body_ of heredoc (misleading field name) */
5515 const char *heredoc = redir->rd_filename;
5516 char *expanded;
5517#if !BB_MMU
5518 char **to_free;
5519#endif
5520
5521 expanded = NULL;
5522 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005523 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005524 if (expanded)
5525 heredoc = expanded;
5526 }
5527 len = strlen(heredoc);
5528
5529 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5530 xpiped_pair(pair);
5531 xmove_fd(pair.rd, redir->rd_fd);
5532
5533 /* Try writing without forking. Newer kernels have
5534 * dynamically growing pipes. Must use non-blocking write! */
5535 ndelay_on(pair.wr);
5536 while (1) {
5537 written = write(pair.wr, heredoc, len);
5538 if (written <= 0)
5539 break;
5540 len -= written;
5541 if (len == 0) {
5542 close(pair.wr);
5543 free(expanded);
5544 return;
5545 }
5546 heredoc += written;
5547 }
5548 ndelay_off(pair.wr);
5549
5550 /* Okay, pipe buffer was not big enough */
5551 /* Note: we must not create a stray child (bastard? :)
5552 * for the unsuspecting parent process. Child creates a grandchild
5553 * and exits before parent execs the process which consumes heredoc
5554 * (that exec happens after we return from this function) */
5555#if !BB_MMU
5556 to_free = NULL;
5557#endif
5558 pid = xvfork();
5559 if (pid == 0) {
5560 /* child */
5561 disable_restore_tty_pgrp_on_exit();
5562 pid = BB_MMU ? xfork() : xvfork();
5563 if (pid != 0)
5564 _exit(0);
5565 /* grandchild */
5566 close(redir->rd_fd); /* read side of the pipe */
5567#if BB_MMU
5568 full_write(pair.wr, heredoc, len); /* may loop or block */
5569 _exit(0);
5570#else
5571 /* Delegate blocking writes to another process */
5572 xmove_fd(pair.wr, STDOUT_FILENO);
5573 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5574#endif
5575 }
5576 /* parent */
5577#if ENABLE_HUSH_FAST
5578 G.count_SIGCHLD++;
5579//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5580#endif
5581 enable_restore_tty_pgrp_on_exit();
5582#if !BB_MMU
5583 free(to_free);
5584#endif
5585 close(pair.wr);
5586 free(expanded);
5587 wait(NULL); /* wait till child has died */
5588}
5589
5590/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5591 * and stderr if they are redirected. */
5592static int setup_redirects(struct command *prog, int squirrel[])
5593{
5594 int openfd, mode;
5595 struct redir_struct *redir;
5596
5597 for (redir = prog->redirects; redir; redir = redir->next) {
5598 if (redir->rd_type == REDIRECT_HEREDOC2) {
5599 /* rd_fd<<HERE case */
5600 if (squirrel && redir->rd_fd < 3
5601 && squirrel[redir->rd_fd] < 0
5602 ) {
5603 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5604 }
5605 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5606 * of the heredoc */
5607 debug_printf_parse("set heredoc '%s'\n",
5608 redir->rd_filename);
5609 setup_heredoc(redir);
5610 continue;
5611 }
5612
5613 if (redir->rd_dup == REDIRFD_TO_FILE) {
5614 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5615 char *p;
5616 if (redir->rd_filename == NULL) {
5617 /* Something went wrong in the parse.
5618 * Pretend it didn't happen */
5619 bb_error_msg("bug in redirect parse");
5620 continue;
5621 }
5622 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005623 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005624 openfd = open_or_warn(p, mode);
5625 free(p);
5626 if (openfd < 0) {
5627 /* this could get lost if stderr has been redirected, but
5628 * bash and ash both lose it as well (though zsh doesn't!) */
5629//what the above comment tries to say?
5630 return 1;
5631 }
5632 } else {
5633 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5634 openfd = redir->rd_dup;
5635 }
5636
5637 if (openfd != redir->rd_fd) {
5638 if (squirrel && redir->rd_fd < 3
5639 && squirrel[redir->rd_fd] < 0
5640 ) {
5641 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5642 }
5643 if (openfd == REDIRFD_CLOSE) {
5644 /* "n>-" means "close me" */
5645 close(redir->rd_fd);
5646 } else {
5647 xdup2(openfd, redir->rd_fd);
5648 if (redir->rd_dup == REDIRFD_TO_FILE)
5649 close(openfd);
5650 }
5651 }
5652 }
5653 return 0;
5654}
5655
5656static void restore_redirects(int squirrel[])
5657{
5658 int i, fd;
5659 for (i = 0; i < 3; i++) {
5660 fd = squirrel[i];
5661 if (fd != -1) {
5662 /* We simply die on error */
5663 xmove_fd(fd, i);
5664 }
5665 }
5666}
5667
5668static char *find_in_path(const char *arg)
5669{
5670 char *ret = NULL;
5671 const char *PATH = get_local_var_value("PATH");
5672
5673 if (!PATH)
5674 return NULL;
5675
5676 while (1) {
5677 const char *end = strchrnul(PATH, ':');
5678 int sz = end - PATH; /* must be int! */
5679
5680 free(ret);
5681 if (sz != 0) {
5682 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5683 } else {
5684 /* We have xxx::yyyy in $PATH,
5685 * it means "use current dir" */
5686 ret = xstrdup(arg);
5687 }
5688 if (access(ret, F_OK) == 0)
5689 break;
5690
5691 if (*end == '\0') {
5692 free(ret);
5693 return NULL;
5694 }
5695 PATH = end + 1;
5696 }
5697
5698 return ret;
5699}
5700
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005701static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005702 const struct built_in_command *x,
5703 const struct built_in_command *end)
5704{
5705 while (x != end) {
5706 if (strcmp(name, x->b_cmd) != 0) {
5707 x++;
5708 continue;
5709 }
5710 debug_printf_exec("found builtin '%s'\n", name);
5711 return x;
5712 }
5713 return NULL;
5714}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005715static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005716{
5717 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5718}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005719static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005720{
5721 const struct built_in_command *x = find_builtin1(name);
5722 if (x)
5723 return x;
5724 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5725}
5726
5727#if ENABLE_HUSH_FUNCTIONS
5728static struct function **find_function_slot(const char *name)
5729{
5730 struct function **funcpp = &G.top_func;
5731 while (*funcpp) {
5732 if (strcmp(name, (*funcpp)->name) == 0) {
5733 break;
5734 }
5735 funcpp = &(*funcpp)->next;
5736 }
5737 return funcpp;
5738}
5739
5740static const struct function *find_function(const char *name)
5741{
5742 const struct function *funcp = *find_function_slot(name);
5743 if (funcp)
5744 debug_printf_exec("found function '%s'\n", name);
5745 return funcp;
5746}
5747
5748/* Note: takes ownership on name ptr */
5749static struct function *new_function(char *name)
5750{
5751 struct function **funcpp = find_function_slot(name);
5752 struct function *funcp = *funcpp;
5753
5754 if (funcp != NULL) {
5755 struct command *cmd = funcp->parent_cmd;
5756 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5757 if (!cmd) {
5758 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5759 free(funcp->name);
5760 /* Note: if !funcp->body, do not free body_as_string!
5761 * This is a special case of "-F name body" function:
5762 * body_as_string was not malloced! */
5763 if (funcp->body) {
5764 free_pipe_list(funcp->body);
5765# if !BB_MMU
5766 free(funcp->body_as_string);
5767# endif
5768 }
5769 } else {
5770 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5771 cmd->argv[0] = funcp->name;
5772 cmd->group = funcp->body;
5773# if !BB_MMU
5774 cmd->group_as_string = funcp->body_as_string;
5775# endif
5776 }
5777 } else {
5778 debug_printf_exec("remembering new function '%s'\n", name);
5779 funcp = *funcpp = xzalloc(sizeof(*funcp));
5780 /*funcp->next = NULL;*/
5781 }
5782
5783 funcp->name = name;
5784 return funcp;
5785}
5786
5787static void unset_func(const char *name)
5788{
5789 struct function **funcpp = find_function_slot(name);
5790 struct function *funcp = *funcpp;
5791
5792 if (funcp != NULL) {
5793 debug_printf_exec("freeing function '%s'\n", funcp->name);
5794 *funcpp = funcp->next;
5795 /* funcp is unlinked now, deleting it.
5796 * Note: if !funcp->body, the function was created by
5797 * "-F name body", do not free ->body_as_string
5798 * and ->name as they were not malloced. */
5799 if (funcp->body) {
5800 free_pipe_list(funcp->body);
5801 free(funcp->name);
5802# if !BB_MMU
5803 free(funcp->body_as_string);
5804# endif
5805 }
5806 free(funcp);
5807 }
5808}
5809
5810# if BB_MMU
5811#define exec_function(to_free, funcp, argv) \
5812 exec_function(funcp, argv)
5813# endif
5814static void exec_function(char ***to_free,
5815 const struct function *funcp,
5816 char **argv) NORETURN;
5817static void exec_function(char ***to_free,
5818 const struct function *funcp,
5819 char **argv)
5820{
5821# if BB_MMU
5822 int n = 1;
5823
5824 argv[0] = G.global_argv[0];
5825 G.global_argv = argv;
5826 while (*++argv)
5827 n++;
5828 G.global_argc = n;
5829 /* On MMU, funcp->body is always non-NULL */
5830 n = run_list(funcp->body);
5831 fflush_all();
5832 _exit(n);
5833# else
5834 re_execute_shell(to_free,
5835 funcp->body_as_string,
5836 G.global_argv[0],
5837 argv + 1,
5838 NULL);
5839# endif
5840}
5841
5842static int run_function(const struct function *funcp, char **argv)
5843{
5844 int rc;
5845 save_arg_t sv;
5846 smallint sv_flg;
5847
5848 save_and_replace_G_args(&sv, argv);
5849
5850 /* "we are in function, ok to use return" */
5851 sv_flg = G.flag_return_in_progress;
5852 G.flag_return_in_progress = -1;
5853# if ENABLE_HUSH_LOCAL
5854 G.func_nest_level++;
5855# endif
5856
5857 /* On MMU, funcp->body is always non-NULL */
5858# if !BB_MMU
5859 if (!funcp->body) {
5860 /* Function defined by -F */
5861 parse_and_run_string(funcp->body_as_string);
5862 rc = G.last_exitcode;
5863 } else
5864# endif
5865 {
5866 rc = run_list(funcp->body);
5867 }
5868
5869# if ENABLE_HUSH_LOCAL
5870 {
5871 struct variable *var;
5872 struct variable **var_pp;
5873
5874 var_pp = &G.top_var;
5875 while ((var = *var_pp) != NULL) {
5876 if (var->func_nest_level < G.func_nest_level) {
5877 var_pp = &var->next;
5878 continue;
5879 }
5880 /* Unexport */
5881 if (var->flg_export)
5882 bb_unsetenv(var->varstr);
5883 /* Remove from global list */
5884 *var_pp = var->next;
5885 /* Free */
5886 if (!var->max_len)
5887 free(var->varstr);
5888 free(var);
5889 }
5890 G.func_nest_level--;
5891 }
5892# endif
5893 G.flag_return_in_progress = sv_flg;
5894
5895 restore_G_args(&sv, argv);
5896
5897 return rc;
5898}
5899#endif /* ENABLE_HUSH_FUNCTIONS */
5900
5901
5902#if BB_MMU
5903#define exec_builtin(to_free, x, argv) \
5904 exec_builtin(x, argv)
5905#else
5906#define exec_builtin(to_free, x, argv) \
5907 exec_builtin(to_free, argv)
5908#endif
5909static void exec_builtin(char ***to_free,
5910 const struct built_in_command *x,
5911 char **argv) NORETURN;
5912static void exec_builtin(char ***to_free,
5913 const struct built_in_command *x,
5914 char **argv)
5915{
5916#if BB_MMU
5917 int rcode = x->b_function(argv);
5918 fflush_all();
5919 _exit(rcode);
5920#else
5921 /* On NOMMU, we must never block!
5922 * Example: { sleep 99 | read line; } & echo Ok
5923 */
5924 re_execute_shell(to_free,
5925 argv[0],
5926 G.global_argv[0],
5927 G.global_argv + 1,
5928 argv);
5929#endif
5930}
5931
5932
5933static void execvp_or_die(char **argv) NORETURN;
5934static void execvp_or_die(char **argv)
5935{
5936 debug_printf_exec("execing '%s'\n", argv[0]);
5937 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5938 execvp(argv[0], argv);
5939 bb_perror_msg("can't execute '%s'", argv[0]);
5940 _exit(127); /* bash compat */
5941}
5942
5943#if ENABLE_HUSH_MODE_X
5944static void dump_cmd_in_x_mode(char **argv)
5945{
5946 if (G_x_mode && argv) {
5947 /* We want to output the line in one write op */
5948 char *buf, *p;
5949 int len;
5950 int n;
5951
5952 len = 3;
5953 n = 0;
5954 while (argv[n])
5955 len += strlen(argv[n++]) + 1;
5956 buf = xmalloc(len);
5957 buf[0] = '+';
5958 p = buf + 1;
5959 n = 0;
5960 while (argv[n])
5961 p += sprintf(p, " %s", argv[n++]);
5962 *p++ = '\n';
5963 *p = '\0';
5964 fputs(buf, stderr);
5965 free(buf);
5966 }
5967}
5968#else
5969# define dump_cmd_in_x_mode(argv) ((void)0)
5970#endif
5971
5972#if BB_MMU
5973#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5974 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5975#define pseudo_exec(nommu_save, command, argv_expanded) \
5976 pseudo_exec(command, argv_expanded)
5977#endif
5978
5979/* Called after [v]fork() in run_pipe, or from builtin_exec.
5980 * Never returns.
5981 * Don't exit() here. If you don't exec, use _exit instead.
5982 * The at_exit handlers apparently confuse the calling process,
5983 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5984static void pseudo_exec_argv(nommu_save_t *nommu_save,
5985 char **argv, int assignment_cnt,
5986 char **argv_expanded) NORETURN;
5987static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5988 char **argv, int assignment_cnt,
5989 char **argv_expanded)
5990{
5991 char **new_env;
5992
5993 new_env = expand_assignments(argv, assignment_cnt);
5994 dump_cmd_in_x_mode(new_env);
5995
5996 if (!argv[assignment_cnt]) {
5997 /* Case when we are here: ... | var=val | ...
5998 * (note that we do not exit early, i.e., do not optimize out
5999 * expand_assignments(): think about ... | var=`sleep 1` | ...
6000 */
6001 free_strings(new_env);
6002 _exit(EXIT_SUCCESS);
6003 }
6004
6005#if BB_MMU
6006 set_vars_and_save_old(new_env);
6007 free(new_env); /* optional */
6008 /* we can also destroy set_vars_and_save_old's return value,
6009 * to save memory */
6010#else
6011 nommu_save->new_env = new_env;
6012 nommu_save->old_vars = set_vars_and_save_old(new_env);
6013#endif
6014
6015 if (argv_expanded) {
6016 argv = argv_expanded;
6017 } else {
6018 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6019#if !BB_MMU
6020 nommu_save->argv = argv;
6021#endif
6022 }
6023 dump_cmd_in_x_mode(argv);
6024
6025#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6026 if (strchr(argv[0], '/') != NULL)
6027 goto skip;
6028#endif
6029
6030 /* Check if the command matches any of the builtins.
6031 * Depending on context, this might be redundant. But it's
6032 * easier to waste a few CPU cycles than it is to figure out
6033 * if this is one of those cases.
6034 */
6035 {
6036 /* On NOMMU, it is more expensive to re-execute shell
6037 * just in order to run echo or test builtin.
6038 * It's better to skip it here and run corresponding
6039 * non-builtin later. */
6040 const struct built_in_command *x;
6041 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6042 if (x) {
6043 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6044 }
6045 }
6046#if ENABLE_HUSH_FUNCTIONS
6047 /* Check if the command matches any functions */
6048 {
6049 const struct function *funcp = find_function(argv[0]);
6050 if (funcp) {
6051 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6052 }
6053 }
6054#endif
6055
6056#if ENABLE_FEATURE_SH_STANDALONE
6057 /* Check if the command matches any busybox applets */
6058 {
6059 int a = find_applet_by_name(argv[0]);
6060 if (a >= 0) {
6061# if BB_MMU /* see above why on NOMMU it is not allowed */
6062 if (APPLET_IS_NOEXEC(a)) {
6063 debug_printf_exec("running applet '%s'\n", argv[0]);
6064 run_applet_no_and_exit(a, argv);
6065 }
6066# endif
6067 /* Re-exec ourselves */
6068 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6069 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6070 execv(bb_busybox_exec_path, argv);
6071 /* If they called chroot or otherwise made the binary no longer
6072 * executable, fall through */
6073 }
6074 }
6075#endif
6076
6077#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6078 skip:
6079#endif
6080 execvp_or_die(argv);
6081}
6082
6083/* Called after [v]fork() in run_pipe
6084 */
6085static void pseudo_exec(nommu_save_t *nommu_save,
6086 struct command *command,
6087 char **argv_expanded) NORETURN;
6088static void pseudo_exec(nommu_save_t *nommu_save,
6089 struct command *command,
6090 char **argv_expanded)
6091{
6092 if (command->argv) {
6093 pseudo_exec_argv(nommu_save, command->argv,
6094 command->assignment_cnt, argv_expanded);
6095 }
6096
6097 if (command->group) {
6098 /* Cases when we are here:
6099 * ( list )
6100 * { list } &
6101 * ... | ( list ) | ...
6102 * ... | { list } | ...
6103 */
6104#if BB_MMU
6105 int rcode;
6106 debug_printf_exec("pseudo_exec: run_list\n");
6107 reset_traps_to_defaults();
6108 rcode = run_list(command->group);
6109 /* OK to leak memory by not calling free_pipe_list,
6110 * since this process is about to exit */
6111 _exit(rcode);
6112#else
6113 re_execute_shell(&nommu_save->argv_from_re_execing,
6114 command->group_as_string,
6115 G.global_argv[0],
6116 G.global_argv + 1,
6117 NULL);
6118#endif
6119 }
6120
6121 /* Case when we are here: ... | >file */
6122 debug_printf_exec("pseudo_exec'ed null command\n");
6123 _exit(EXIT_SUCCESS);
6124}
6125
6126#if ENABLE_HUSH_JOB
6127static const char *get_cmdtext(struct pipe *pi)
6128{
6129 char **argv;
6130 char *p;
6131 int len;
6132
6133 /* This is subtle. ->cmdtext is created only on first backgrounding.
6134 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6135 * On subsequent bg argv is trashed, but we won't use it */
6136 if (pi->cmdtext)
6137 return pi->cmdtext;
6138 argv = pi->cmds[0].argv;
6139 if (!argv || !argv[0]) {
6140 pi->cmdtext = xzalloc(1);
6141 return pi->cmdtext;
6142 }
6143
6144 len = 0;
6145 do {
6146 len += strlen(*argv) + 1;
6147 } while (*++argv);
6148 p = xmalloc(len);
6149 pi->cmdtext = p;
6150 argv = pi->cmds[0].argv;
6151 do {
6152 len = strlen(*argv);
6153 memcpy(p, *argv, len);
6154 p += len;
6155 *p++ = ' ';
6156 } while (*++argv);
6157 p[-1] = '\0';
6158 return pi->cmdtext;
6159}
6160
6161static void insert_bg_job(struct pipe *pi)
6162{
6163 struct pipe *job, **jobp;
6164 int i;
6165
6166 /* Linear search for the ID of the job to use */
6167 pi->jobid = 1;
6168 for (job = G.job_list; job; job = job->next)
6169 if (job->jobid >= pi->jobid)
6170 pi->jobid = job->jobid + 1;
6171
6172 /* Add job to the list of running jobs */
6173 jobp = &G.job_list;
6174 while ((job = *jobp) != NULL)
6175 jobp = &job->next;
6176 job = *jobp = xmalloc(sizeof(*job));
6177
6178 *job = *pi; /* physical copy */
6179 job->next = NULL;
6180 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6181 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6182 for (i = 0; i < pi->num_cmds; i++) {
6183 job->cmds[i].pid = pi->cmds[i].pid;
6184 /* all other fields are not used and stay zero */
6185 }
6186 job->cmdtext = xstrdup(get_cmdtext(pi));
6187
6188 if (G_interactive_fd)
6189 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6190 G.last_jobid = job->jobid;
6191}
6192
6193static void remove_bg_job(struct pipe *pi)
6194{
6195 struct pipe *prev_pipe;
6196
6197 if (pi == G.job_list) {
6198 G.job_list = pi->next;
6199 } else {
6200 prev_pipe = G.job_list;
6201 while (prev_pipe->next != pi)
6202 prev_pipe = prev_pipe->next;
6203 prev_pipe->next = pi->next;
6204 }
6205 if (G.job_list)
6206 G.last_jobid = G.job_list->jobid;
6207 else
6208 G.last_jobid = 0;
6209}
6210
6211/* Remove a backgrounded job */
6212static void delete_finished_bg_job(struct pipe *pi)
6213{
6214 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006215 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006216}
6217#endif /* JOB */
6218
6219/* Check to see if any processes have exited -- if they
6220 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006221static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006222{
6223 int attributes;
6224 int status;
6225#if ENABLE_HUSH_JOB
6226 struct pipe *pi;
6227#endif
6228 pid_t childpid;
6229 int rcode = 0;
6230
6231 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6232
6233 attributes = WUNTRACED;
6234 if (fg_pipe == NULL)
6235 attributes |= WNOHANG;
6236
6237 errno = 0;
6238#if ENABLE_HUSH_FAST
6239 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6240//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6241//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6242 /* There was neither fork nor SIGCHLD since last waitpid */
6243 /* Avoid doing waitpid syscall if possible */
6244 if (!G.we_have_children) {
6245 errno = ECHILD;
6246 return -1;
6247 }
6248 if (fg_pipe == NULL) { /* is WNOHANG set? */
6249 /* We have children, but they did not exit
6250 * or stop yet (we saw no SIGCHLD) */
6251 return 0;
6252 }
6253 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6254 }
6255#endif
6256
6257/* Do we do this right?
6258 * bash-3.00# sleep 20 | false
6259 * <ctrl-Z pressed>
6260 * [3]+ Stopped sleep 20 | false
6261 * bash-3.00# echo $?
6262 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6263 * [hush 1.14.0: yes we do it right]
6264 */
6265 wait_more:
6266 while (1) {
6267 int i;
6268 int dead;
6269
6270#if ENABLE_HUSH_FAST
6271 i = G.count_SIGCHLD;
6272#endif
6273 childpid = waitpid(-1, &status, attributes);
6274 if (childpid <= 0) {
6275 if (childpid && errno != ECHILD)
6276 bb_perror_msg("waitpid");
6277#if ENABLE_HUSH_FAST
6278 else { /* Until next SIGCHLD, waitpid's are useless */
6279 G.we_have_children = (childpid == 0);
6280 G.handled_SIGCHLD = i;
6281//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6282 }
6283#endif
6284 break;
6285 }
6286 dead = WIFEXITED(status) || WIFSIGNALED(status);
6287
6288#if DEBUG_JOBS
6289 if (WIFSTOPPED(status))
6290 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6291 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6292 if (WIFSIGNALED(status))
6293 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6294 childpid, WTERMSIG(status), WEXITSTATUS(status));
6295 if (WIFEXITED(status))
6296 debug_printf_jobs("pid %d exited, exitcode %d\n",
6297 childpid, WEXITSTATUS(status));
6298#endif
6299 /* Were we asked to wait for fg pipe? */
6300 if (fg_pipe) {
6301 for (i = 0; i < fg_pipe->num_cmds; i++) {
6302 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6303 if (fg_pipe->cmds[i].pid != childpid)
6304 continue;
6305 if (dead) {
6306 fg_pipe->cmds[i].pid = 0;
6307 fg_pipe->alive_cmds--;
6308 if (i == fg_pipe->num_cmds - 1) {
6309 /* last process gives overall exitstatus */
6310 rcode = WEXITSTATUS(status);
6311 /* bash prints killer signal's name for *last*
6312 * process in pipe (prints just newline for SIGINT).
6313 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6314 */
6315 if (WIFSIGNALED(status)) {
6316 int sig = WTERMSIG(status);
6317 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6318 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6319 * Maybe we need to use sig | 128? */
6320 rcode = sig + 128;
6321 }
6322 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6323 }
6324 } else {
6325 fg_pipe->cmds[i].is_stopped = 1;
6326 fg_pipe->stopped_cmds++;
6327 }
6328 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6329 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6330 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6331 /* All processes in fg pipe have exited or stopped */
6332/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6333 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6334 * and "killall -STOP cat" */
6335 if (G_interactive_fd) {
6336#if ENABLE_HUSH_JOB
6337 if (fg_pipe->alive_cmds)
6338 insert_bg_job(fg_pipe);
6339#endif
6340 return rcode;
6341 }
6342 if (!fg_pipe->alive_cmds)
6343 return rcode;
6344 }
6345 /* There are still running processes in the fg pipe */
6346 goto wait_more; /* do waitpid again */
6347 }
6348 /* it wasnt fg_pipe, look for process in bg pipes */
6349 }
6350
6351#if ENABLE_HUSH_JOB
6352 /* We asked to wait for bg or orphaned children */
6353 /* No need to remember exitcode in this case */
6354 for (pi = G.job_list; pi; pi = pi->next) {
6355 for (i = 0; i < pi->num_cmds; i++) {
6356 if (pi->cmds[i].pid == childpid)
6357 goto found_pi_and_prognum;
6358 }
6359 }
6360 /* Happens when shell is used as init process (init=/bin/sh) */
6361 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6362 continue; /* do waitpid again */
6363
6364 found_pi_and_prognum:
6365 if (dead) {
6366 /* child exited */
6367 pi->cmds[i].pid = 0;
6368 pi->alive_cmds--;
6369 if (!pi->alive_cmds) {
6370 if (G_interactive_fd)
6371 printf(JOB_STATUS_FORMAT, pi->jobid,
6372 "Done", pi->cmdtext);
6373 delete_finished_bg_job(pi);
6374 }
6375 } else {
6376 /* child stopped */
6377 pi->cmds[i].is_stopped = 1;
6378 pi->stopped_cmds++;
6379 }
6380#endif
6381 } /* while (waitpid succeeds)... */
6382
6383 return rcode;
6384}
6385
6386#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006387static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006388{
6389 pid_t p;
6390 int rcode = checkjobs(fg_pipe);
6391 if (G_saved_tty_pgrp) {
6392 /* Job finished, move the shell to the foreground */
6393 p = getpgrp(); /* our process group id */
6394 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6395 tcsetpgrp(G_interactive_fd, p);
6396 }
6397 return rcode;
6398}
6399#endif
6400
6401/* Start all the jobs, but don't wait for anything to finish.
6402 * See checkjobs().
6403 *
6404 * Return code is normally -1, when the caller has to wait for children
6405 * to finish to determine the exit status of the pipe. If the pipe
6406 * is a simple builtin command, however, the action is done by the
6407 * time run_pipe returns, and the exit code is provided as the
6408 * return value.
6409 *
6410 * Returns -1 only if started some children. IOW: we have to
6411 * mask out retvals of builtins etc with 0xff!
6412 *
6413 * The only case when we do not need to [v]fork is when the pipe
6414 * is single, non-backgrounded, non-subshell command. Examples:
6415 * cmd ; ... { list } ; ...
6416 * cmd && ... { list } && ...
6417 * cmd || ... { list } || ...
6418 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6419 * or (if SH_STANDALONE) an applet, and we can run the { list }
6420 * with run_list. If it isn't one of these, we fork and exec cmd.
6421 *
6422 * Cases when we must fork:
6423 * non-single: cmd | cmd
6424 * backgrounded: cmd & { list } &
6425 * subshell: ( list ) [&]
6426 */
6427#if !ENABLE_HUSH_MODE_X
6428#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6429 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6430#endif
6431static int redirect_and_varexp_helper(char ***new_env_p,
6432 struct variable **old_vars_p,
6433 struct command *command,
6434 int squirrel[3],
6435 char **argv_expanded)
6436{
6437 /* setup_redirects acts on file descriptors, not FILEs.
6438 * This is perfect for work that comes after exec().
6439 * Is it really safe for inline use? Experimentally,
6440 * things seem to work. */
6441 int rcode = setup_redirects(command, squirrel);
6442 if (rcode == 0) {
6443 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6444 *new_env_p = new_env;
6445 dump_cmd_in_x_mode(new_env);
6446 dump_cmd_in_x_mode(argv_expanded);
6447 if (old_vars_p)
6448 *old_vars_p = set_vars_and_save_old(new_env);
6449 }
6450 return rcode;
6451}
6452static NOINLINE int run_pipe(struct pipe *pi)
6453{
6454 static const char *const null_ptr = NULL;
6455
6456 int cmd_no;
6457 int next_infd;
6458 struct command *command;
6459 char **argv_expanded;
6460 char **argv;
6461 /* it is not always needed, but we aim to smaller code */
6462 int squirrel[] = { -1, -1, -1 };
6463 int rcode;
6464
6465 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6466 debug_enter();
6467
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006468 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6469 * Result should be 3 lines: q w e, qwe, q w e
6470 */
6471 G.ifs = get_local_var_value("IFS");
6472 if (!G.ifs)
6473 G.ifs = defifs;
6474
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006475 IF_HUSH_JOB(pi->pgrp = -1;)
6476 pi->stopped_cmds = 0;
6477 command = &pi->cmds[0];
6478 argv_expanded = NULL;
6479
6480 if (pi->num_cmds != 1
6481 || pi->followup == PIPE_BG
6482 || command->cmd_type == CMD_SUBSHELL
6483 ) {
6484 goto must_fork;
6485 }
6486
6487 pi->alive_cmds = 1;
6488
6489 debug_printf_exec(": group:%p argv:'%s'\n",
6490 command->group, command->argv ? command->argv[0] : "NONE");
6491
6492 if (command->group) {
6493#if ENABLE_HUSH_FUNCTIONS
6494 if (command->cmd_type == CMD_FUNCDEF) {
6495 /* "executing" func () { list } */
6496 struct function *funcp;
6497
6498 funcp = new_function(command->argv[0]);
6499 /* funcp->name is already set to argv[0] */
6500 funcp->body = command->group;
6501# if !BB_MMU
6502 funcp->body_as_string = command->group_as_string;
6503 command->group_as_string = NULL;
6504# endif
6505 command->group = NULL;
6506 command->argv[0] = NULL;
6507 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6508 funcp->parent_cmd = command;
6509 command->child_func = funcp;
6510
6511 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6512 debug_leave();
6513 return EXIT_SUCCESS;
6514 }
6515#endif
6516 /* { list } */
6517 debug_printf("non-subshell group\n");
6518 rcode = 1; /* exitcode if redir failed */
6519 if (setup_redirects(command, squirrel) == 0) {
6520 debug_printf_exec(": run_list\n");
6521 rcode = run_list(command->group) & 0xff;
6522 }
6523 restore_redirects(squirrel);
6524 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6525 debug_leave();
6526 debug_printf_exec("run_pipe: return %d\n", rcode);
6527 return rcode;
6528 }
6529
6530 argv = command->argv ? command->argv : (char **) &null_ptr;
6531 {
6532 const struct built_in_command *x;
6533#if ENABLE_HUSH_FUNCTIONS
6534 const struct function *funcp;
6535#else
6536 enum { funcp = 0 };
6537#endif
6538 char **new_env = NULL;
6539 struct variable *old_vars = NULL;
6540
6541 if (argv[command->assignment_cnt] == NULL) {
6542 /* Assignments, but no command */
6543 /* Ensure redirects take effect (that is, create files).
6544 * Try "a=t >file" */
6545#if 0 /* A few cases in testsuite fail with this code. FIXME */
6546 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6547 /* Set shell variables */
6548 if (new_env) {
6549 argv = new_env;
6550 while (*argv) {
6551 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6552 /* Do we need to flag set_local_var() errors?
6553 * "assignment to readonly var" and "putenv error"
6554 */
6555 argv++;
6556 }
6557 }
6558 /* Redirect error sets $? to 1. Otherwise,
6559 * if evaluating assignment value set $?, retain it.
6560 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6561 if (rcode == 0)
6562 rcode = G.last_exitcode;
6563 /* Exit, _skipping_ variable restoring code: */
6564 goto clean_up_and_ret0;
6565
6566#else /* Older, bigger, but more correct code */
6567
6568 rcode = setup_redirects(command, squirrel);
6569 restore_redirects(squirrel);
6570 /* Set shell variables */
6571 if (G_x_mode)
6572 bb_putchar_stderr('+');
6573 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006574 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006575 if (G_x_mode)
6576 fprintf(stderr, " %s", p);
6577 debug_printf_exec("set shell var:'%s'->'%s'\n",
6578 *argv, p);
6579 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6580 /* Do we need to flag set_local_var() errors?
6581 * "assignment to readonly var" and "putenv error"
6582 */
6583 argv++;
6584 }
6585 if (G_x_mode)
6586 bb_putchar_stderr('\n');
6587 /* Redirect error sets $? to 1. Otherwise,
6588 * if evaluating assignment value set $?, retain it.
6589 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6590 if (rcode == 0)
6591 rcode = G.last_exitcode;
6592 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6593 debug_leave();
6594 debug_printf_exec("run_pipe: return %d\n", rcode);
6595 return rcode;
6596#endif
6597 }
6598
6599 /* Expand the rest into (possibly) many strings each */
6600 if (0) {}
6601#if ENABLE_HUSH_BASH_COMPAT
6602 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6603 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6604 }
6605#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006606 else {
6607 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6608 }
6609
6610 /* if someone gives us an empty string: `cmd with empty output` */
6611 if (!argv_expanded[0]) {
6612 free(argv_expanded);
6613 debug_leave();
6614 return G.last_exitcode;
6615 }
6616
6617 x = find_builtin(argv_expanded[0]);
6618#if ENABLE_HUSH_FUNCTIONS
6619 funcp = NULL;
6620 if (!x)
6621 funcp = find_function(argv_expanded[0]);
6622#endif
6623 if (x || funcp) {
6624 if (!funcp) {
6625 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6626 debug_printf("exec with redirects only\n");
6627 rcode = setup_redirects(command, NULL);
6628 goto clean_up_and_ret1;
6629 }
6630 }
6631 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6632 if (rcode == 0) {
6633 if (!funcp) {
6634 debug_printf_exec(": builtin '%s' '%s'...\n",
6635 x->b_cmd, argv_expanded[1]);
6636 rcode = x->b_function(argv_expanded) & 0xff;
6637 fflush_all();
6638 }
6639#if ENABLE_HUSH_FUNCTIONS
6640 else {
6641# if ENABLE_HUSH_LOCAL
6642 struct variable **sv;
6643 sv = G.shadowed_vars_pp;
6644 G.shadowed_vars_pp = &old_vars;
6645# endif
6646 debug_printf_exec(": function '%s' '%s'...\n",
6647 funcp->name, argv_expanded[1]);
6648 rcode = run_function(funcp, argv_expanded) & 0xff;
6649# if ENABLE_HUSH_LOCAL
6650 G.shadowed_vars_pp = sv;
6651# endif
6652 }
6653#endif
6654 }
6655 clean_up_and_ret:
6656 unset_vars(new_env);
6657 add_vars(old_vars);
6658/* clean_up_and_ret0: */
6659 restore_redirects(squirrel);
6660 clean_up_and_ret1:
6661 free(argv_expanded);
6662 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6663 debug_leave();
6664 debug_printf_exec("run_pipe return %d\n", rcode);
6665 return rcode;
6666 }
6667
6668 if (ENABLE_FEATURE_SH_STANDALONE) {
6669 int n = find_applet_by_name(argv_expanded[0]);
6670 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6671 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6672 if (rcode == 0) {
6673 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6674 argv_expanded[0], argv_expanded[1]);
6675 rcode = run_nofork_applet(n, argv_expanded);
6676 }
6677 goto clean_up_and_ret;
6678 }
6679 }
6680 /* It is neither builtin nor applet. We must fork. */
6681 }
6682
6683 must_fork:
6684 /* NB: argv_expanded may already be created, and that
6685 * might include `cmd` runs! Do not rerun it! We *must*
6686 * use argv_expanded if it's non-NULL */
6687
6688 /* Going to fork a child per each pipe member */
6689 pi->alive_cmds = 0;
6690 next_infd = 0;
6691
6692 cmd_no = 0;
6693 while (cmd_no < pi->num_cmds) {
6694 struct fd_pair pipefds;
6695#if !BB_MMU
6696 volatile nommu_save_t nommu_save;
6697 nommu_save.new_env = NULL;
6698 nommu_save.old_vars = NULL;
6699 nommu_save.argv = NULL;
6700 nommu_save.argv_from_re_execing = NULL;
6701#endif
6702 command = &pi->cmds[cmd_no];
6703 cmd_no++;
6704 if (command->argv) {
6705 debug_printf_exec(": pipe member '%s' '%s'...\n",
6706 command->argv[0], command->argv[1]);
6707 } else {
6708 debug_printf_exec(": pipe member with no argv\n");
6709 }
6710
6711 /* pipes are inserted between pairs of commands */
6712 pipefds.rd = 0;
6713 pipefds.wr = 1;
6714 if (cmd_no < pi->num_cmds)
6715 xpiped_pair(pipefds);
6716
6717 command->pid = BB_MMU ? fork() : vfork();
6718 if (!command->pid) { /* child */
6719#if ENABLE_HUSH_JOB
6720 disable_restore_tty_pgrp_on_exit();
6721 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6722
6723 /* Every child adds itself to new process group
6724 * with pgid == pid_of_first_child_in_pipe */
6725 if (G.run_list_level == 1 && G_interactive_fd) {
6726 pid_t pgrp;
6727 pgrp = pi->pgrp;
6728 if (pgrp < 0) /* true for 1st process only */
6729 pgrp = getpid();
6730 if (setpgid(0, pgrp) == 0
6731 && pi->followup != PIPE_BG
6732 && G_saved_tty_pgrp /* we have ctty */
6733 ) {
6734 /* We do it in *every* child, not just first,
6735 * to avoid races */
6736 tcsetpgrp(G_interactive_fd, pgrp);
6737 }
6738 }
6739#endif
6740 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6741 /* 1st cmd in backgrounded pipe
6742 * should have its stdin /dev/null'ed */
6743 close(0);
6744 if (open(bb_dev_null, O_RDONLY))
6745 xopen("/", O_RDONLY);
6746 } else {
6747 xmove_fd(next_infd, 0);
6748 }
6749 xmove_fd(pipefds.wr, 1);
6750 if (pipefds.rd > 1)
6751 close(pipefds.rd);
6752 /* Like bash, explicit redirects override pipes,
6753 * and the pipe fd is available for dup'ing. */
6754 if (setup_redirects(command, NULL))
6755 _exit(1);
6756
6757 /* Restore default handlers just prior to exec */
6758 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6759
6760 /* Stores to nommu_save list of env vars putenv'ed
6761 * (NOMMU, on MMU we don't need that) */
6762 /* cast away volatility... */
6763 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6764 /* pseudo_exec() does not return */
6765 }
6766
6767 /* parent or error */
6768#if ENABLE_HUSH_FAST
6769 G.count_SIGCHLD++;
6770//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6771#endif
6772 enable_restore_tty_pgrp_on_exit();
6773#if !BB_MMU
6774 /* Clean up after vforked child */
6775 free(nommu_save.argv);
6776 free(nommu_save.argv_from_re_execing);
6777 unset_vars(nommu_save.new_env);
6778 add_vars(nommu_save.old_vars);
6779#endif
6780 free(argv_expanded);
6781 argv_expanded = NULL;
6782 if (command->pid < 0) { /* [v]fork failed */
6783 /* Clearly indicate, was it fork or vfork */
6784 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6785 } else {
6786 pi->alive_cmds++;
6787#if ENABLE_HUSH_JOB
6788 /* Second and next children need to know pid of first one */
6789 if (pi->pgrp < 0)
6790 pi->pgrp = command->pid;
6791#endif
6792 }
6793
6794 if (cmd_no > 1)
6795 close(next_infd);
6796 if (cmd_no < pi->num_cmds)
6797 close(pipefds.wr);
6798 /* Pass read (output) pipe end to next iteration */
6799 next_infd = pipefds.rd;
6800 }
6801
6802 if (!pi->alive_cmds) {
6803 debug_leave();
6804 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6805 return 1;
6806 }
6807
6808 debug_leave();
6809 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6810 return -1;
6811}
6812
6813#ifndef debug_print_tree
6814static void debug_print_tree(struct pipe *pi, int lvl)
6815{
6816 static const char *const PIPE[] = {
6817 [PIPE_SEQ] = "SEQ",
6818 [PIPE_AND] = "AND",
6819 [PIPE_OR ] = "OR" ,
6820 [PIPE_BG ] = "BG" ,
6821 };
6822 static const char *RES[] = {
6823 [RES_NONE ] = "NONE" ,
6824# if ENABLE_HUSH_IF
6825 [RES_IF ] = "IF" ,
6826 [RES_THEN ] = "THEN" ,
6827 [RES_ELIF ] = "ELIF" ,
6828 [RES_ELSE ] = "ELSE" ,
6829 [RES_FI ] = "FI" ,
6830# endif
6831# if ENABLE_HUSH_LOOPS
6832 [RES_FOR ] = "FOR" ,
6833 [RES_WHILE] = "WHILE",
6834 [RES_UNTIL] = "UNTIL",
6835 [RES_DO ] = "DO" ,
6836 [RES_DONE ] = "DONE" ,
6837# endif
6838# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6839 [RES_IN ] = "IN" ,
6840# endif
6841# if ENABLE_HUSH_CASE
6842 [RES_CASE ] = "CASE" ,
6843 [RES_CASE_IN ] = "CASE_IN" ,
6844 [RES_MATCH] = "MATCH",
6845 [RES_CASE_BODY] = "CASE_BODY",
6846 [RES_ESAC ] = "ESAC" ,
6847# endif
6848 [RES_XXXX ] = "XXXX" ,
6849 [RES_SNTX ] = "SNTX" ,
6850 };
6851 static const char *const CMDTYPE[] = {
6852 "{}",
6853 "()",
6854 "[noglob]",
6855# if ENABLE_HUSH_FUNCTIONS
6856 "func()",
6857# endif
6858 };
6859
6860 int pin, prn;
6861
6862 pin = 0;
6863 while (pi) {
6864 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6865 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6866 prn = 0;
6867 while (prn < pi->num_cmds) {
6868 struct command *command = &pi->cmds[prn];
6869 char **argv = command->argv;
6870
6871 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6872 lvl*2, "", prn,
6873 command->assignment_cnt);
6874 if (command->group) {
6875 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6876 CMDTYPE[command->cmd_type],
6877 argv
6878# if !BB_MMU
6879 , " group_as_string:", command->group_as_string
6880# else
6881 , "", ""
6882# endif
6883 );
6884 debug_print_tree(command->group, lvl+1);
6885 prn++;
6886 continue;
6887 }
6888 if (argv) while (*argv) {
6889 fprintf(stderr, " '%s'", *argv);
6890 argv++;
6891 }
6892 fprintf(stderr, "\n");
6893 prn++;
6894 }
6895 pi = pi->next;
6896 pin++;
6897 }
6898}
6899#endif /* debug_print_tree */
6900
6901/* NB: called by pseudo_exec, and therefore must not modify any
6902 * global data until exec/_exit (we can be a child after vfork!) */
6903static int run_list(struct pipe *pi)
6904{
6905#if ENABLE_HUSH_CASE
6906 char *case_word = NULL;
6907#endif
6908#if ENABLE_HUSH_LOOPS
6909 struct pipe *loop_top = NULL;
6910 char **for_lcur = NULL;
6911 char **for_list = NULL;
6912#endif
6913 smallint last_followup;
6914 smalluint rcode;
6915#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6916 smalluint cond_code = 0;
6917#else
6918 enum { cond_code = 0 };
6919#endif
6920#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02006921 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006922 smallint last_rword; /* ditto */
6923#endif
6924
6925 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6926 debug_enter();
6927
6928#if ENABLE_HUSH_LOOPS
6929 /* Check syntax for "for" */
6930 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6931 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6932 continue;
6933 /* current word is FOR or IN (BOLD in comments below) */
6934 if (cpipe->next == NULL) {
6935 syntax_error("malformed for");
6936 debug_leave();
6937 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6938 return 1;
6939 }
6940 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6941 if (cpipe->next->res_word == RES_DO)
6942 continue;
6943 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6944 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6945 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6946 ) {
6947 syntax_error("malformed for");
6948 debug_leave();
6949 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6950 return 1;
6951 }
6952 }
6953#endif
6954
6955 /* Past this point, all code paths should jump to ret: label
6956 * in order to return, no direct "return" statements please.
6957 * This helps to ensure that no memory is leaked. */
6958
6959#if ENABLE_HUSH_JOB
6960 G.run_list_level++;
6961#endif
6962
6963#if HAS_KEYWORDS
6964 rword = RES_NONE;
6965 last_rword = RES_XXXX;
6966#endif
6967 last_followup = PIPE_SEQ;
6968 rcode = G.last_exitcode;
6969
6970 /* Go through list of pipes, (maybe) executing them. */
6971 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6972 if (G.flag_SIGINT)
6973 break;
6974
6975 IF_HAS_KEYWORDS(rword = pi->res_word;)
6976 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6977 rword, cond_code, last_rword);
6978#if ENABLE_HUSH_LOOPS
6979 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6980 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6981 ) {
6982 /* start of a loop: remember where loop starts */
6983 loop_top = pi;
6984 G.depth_of_loop++;
6985 }
6986#endif
6987 /* Still in the same "if...", "then..." or "do..." branch? */
6988 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6989 if ((rcode == 0 && last_followup == PIPE_OR)
6990 || (rcode != 0 && last_followup == PIPE_AND)
6991 ) {
6992 /* It is "<true> || CMD" or "<false> && CMD"
6993 * and we should not execute CMD */
6994 debug_printf_exec("skipped cmd because of || or &&\n");
6995 last_followup = pi->followup;
6996 continue;
6997 }
6998 }
6999 last_followup = pi->followup;
7000 IF_HAS_KEYWORDS(last_rword = rword;)
7001#if ENABLE_HUSH_IF
7002 if (cond_code) {
7003 if (rword == RES_THEN) {
7004 /* if false; then ... fi has exitcode 0! */
7005 G.last_exitcode = rcode = EXIT_SUCCESS;
7006 /* "if <false> THEN cmd": skip cmd */
7007 continue;
7008 }
7009 } else {
7010 if (rword == RES_ELSE || rword == RES_ELIF) {
7011 /* "if <true> then ... ELSE/ELIF cmd":
7012 * skip cmd and all following ones */
7013 break;
7014 }
7015 }
7016#endif
7017#if ENABLE_HUSH_LOOPS
7018 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7019 if (!for_lcur) {
7020 /* first loop through for */
7021
7022 static const char encoded_dollar_at[] ALIGN1 = {
7023 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7024 }; /* encoded representation of "$@" */
7025 static const char *const encoded_dollar_at_argv[] = {
7026 encoded_dollar_at, NULL
7027 }; /* argv list with one element: "$@" */
7028 char **vals;
7029
7030 vals = (char**)encoded_dollar_at_argv;
7031 if (pi->next->res_word == RES_IN) {
7032 /* if no variable values after "in" we skip "for" */
7033 if (!pi->next->cmds[0].argv) {
7034 G.last_exitcode = rcode = EXIT_SUCCESS;
7035 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7036 break;
7037 }
7038 vals = pi->next->cmds[0].argv;
7039 } /* else: "for var; do..." -> assume "$@" list */
7040 /* create list of variable values */
7041 debug_print_strings("for_list made from", vals);
7042 for_list = expand_strvec_to_strvec(vals);
7043 for_lcur = for_list;
7044 debug_print_strings("for_list", for_list);
7045 }
7046 if (!*for_lcur) {
7047 /* "for" loop is over, clean up */
7048 free(for_list);
7049 for_list = NULL;
7050 for_lcur = NULL;
7051 break;
7052 }
7053 /* Insert next value from for_lcur */
7054 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7055 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7056 continue;
7057 }
7058 if (rword == RES_IN) {
7059 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7060 }
7061 if (rword == RES_DONE) {
7062 continue; /* "done" has no cmds too */
7063 }
7064#endif
7065#if ENABLE_HUSH_CASE
7066 if (rword == RES_CASE) {
7067 case_word = expand_strvec_to_string(pi->cmds->argv);
7068 continue;
7069 }
7070 if (rword == RES_MATCH) {
7071 char **argv;
7072
7073 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7074 break;
7075 /* all prev words didn't match, does this one match? */
7076 argv = pi->cmds->argv;
7077 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007078 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007079 /* TODO: which FNM_xxx flags to use? */
7080 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7081 free(pattern);
7082 if (cond_code == 0) { /* match! we will execute this branch */
7083 free(case_word); /* make future "word)" stop */
7084 case_word = NULL;
7085 break;
7086 }
7087 argv++;
7088 }
7089 continue;
7090 }
7091 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7092 if (cond_code != 0)
7093 continue; /* not matched yet, skip this pipe */
7094 }
7095#endif
7096 /* Just pressing <enter> in shell should check for jobs.
7097 * OTOH, in non-interactive shell this is useless
7098 * and only leads to extra job checks */
7099 if (pi->num_cmds == 0) {
7100 if (G_interactive_fd)
7101 goto check_jobs_and_continue;
7102 continue;
7103 }
7104
7105 /* After analyzing all keywords and conditions, we decided
7106 * to execute this pipe. NB: have to do checkjobs(NULL)
7107 * after run_pipe to collect any background children,
7108 * even if list execution is to be stopped. */
7109 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7110 {
7111 int r;
7112#if ENABLE_HUSH_LOOPS
7113 G.flag_break_continue = 0;
7114#endif
7115 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7116 if (r != -1) {
7117 /* We ran a builtin, function, or group.
7118 * rcode is already known
7119 * and we don't need to wait for anything. */
7120 G.last_exitcode = rcode;
7121 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7122 check_and_run_traps(0);
7123#if ENABLE_HUSH_LOOPS
7124 /* Was it "break" or "continue"? */
7125 if (G.flag_break_continue) {
7126 smallint fbc = G.flag_break_continue;
7127 /* We might fall into outer *loop*,
7128 * don't want to break it too */
7129 if (loop_top) {
7130 G.depth_break_continue--;
7131 if (G.depth_break_continue == 0)
7132 G.flag_break_continue = 0;
7133 /* else: e.g. "continue 2" should *break* once, *then* continue */
7134 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7135 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7136 goto check_jobs_and_break;
7137 /* "continue": simulate end of loop */
7138 rword = RES_DONE;
7139 continue;
7140 }
7141#endif
7142#if ENABLE_HUSH_FUNCTIONS
7143 if (G.flag_return_in_progress == 1) {
7144 /* same as "goto check_jobs_and_break" */
7145 checkjobs(NULL);
7146 break;
7147 }
7148#endif
7149 } else if (pi->followup == PIPE_BG) {
7150 /* What does bash do with attempts to background builtins? */
7151 /* even bash 3.2 doesn't do that well with nested bg:
7152 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7153 * I'm NOT treating inner &'s as jobs */
7154 check_and_run_traps(0);
7155#if ENABLE_HUSH_JOB
7156 if (G.run_list_level == 1)
7157 insert_bg_job(pi);
7158#endif
7159 /* Last command's pid goes to $! */
7160 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7161 G.last_exitcode = rcode = EXIT_SUCCESS;
7162 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7163 } else {
7164#if ENABLE_HUSH_JOB
7165 if (G.run_list_level == 1 && G_interactive_fd) {
7166 /* Waits for completion, then fg's main shell */
7167 rcode = checkjobs_and_fg_shell(pi);
7168 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7169 check_and_run_traps(0);
7170 } else
7171#endif
7172 { /* This one just waits for completion */
7173 rcode = checkjobs(pi);
7174 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7175 check_and_run_traps(0);
7176 }
7177 G.last_exitcode = rcode;
7178 }
7179 }
7180
7181 /* Analyze how result affects subsequent commands */
7182#if ENABLE_HUSH_IF
7183 if (rword == RES_IF || rword == RES_ELIF)
7184 cond_code = rcode;
7185#endif
7186#if ENABLE_HUSH_LOOPS
7187 /* Beware of "while false; true; do ..."! */
7188 if (pi->next && pi->next->res_word == RES_DO) {
7189 if (rword == RES_WHILE) {
7190 if (rcode) {
7191 /* "while false; do...done" - exitcode 0 */
7192 G.last_exitcode = rcode = EXIT_SUCCESS;
7193 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7194 goto check_jobs_and_break;
7195 }
7196 }
7197 if (rword == RES_UNTIL) {
7198 if (!rcode) {
7199 debug_printf_exec(": until expr is true: breaking\n");
7200 check_jobs_and_break:
7201 checkjobs(NULL);
7202 break;
7203 }
7204 }
7205 }
7206#endif
7207
7208 check_jobs_and_continue:
7209 checkjobs(NULL);
7210 } /* for (pi) */
7211
7212#if ENABLE_HUSH_JOB
7213 G.run_list_level--;
7214#endif
7215#if ENABLE_HUSH_LOOPS
7216 if (loop_top)
7217 G.depth_of_loop--;
7218 free(for_list);
7219#endif
7220#if ENABLE_HUSH_CASE
7221 free(case_word);
7222#endif
7223 debug_leave();
7224 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7225 return rcode;
7226}
7227
7228/* Select which version we will use */
7229static int run_and_free_list(struct pipe *pi)
7230{
7231 int rcode = 0;
7232 debug_printf_exec("run_and_free_list entered\n");
7233 if (!G.n_mode) {
7234 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7235 rcode = run_list(pi);
7236 }
7237 /* free_pipe_list has the side effect of clearing memory.
7238 * In the long run that function can be merged with run_list,
7239 * but doing that now would hobble the debugging effort. */
7240 free_pipe_list(pi);
7241 debug_printf_exec("run_and_free_list return %d\n", rcode);
7242 return rcode;
7243}
7244
7245
Denis Vlasenkof9375282009-04-05 19:13:39 +00007246/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007247static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007248{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007249 unsigned sig;
7250 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007251 sigset_t old_blocked_set;
7252
7253 if (!G.inherited_set_is_saved) {
7254 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7255 G.inherited_set = G.blocked_set;
7256 }
7257 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007258
Denis Vlasenkof9375282009-04-05 19:13:39 +00007259 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007260 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007261 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007262 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007263 mask |= SPECIAL_JOB_SIGS;
7264 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007265 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007266
Denis Vlasenkof9375282009-04-05 19:13:39 +00007267 sig = 0;
7268 while (mask) {
7269 if (mask & 1)
7270 sigaddset(&G.blocked_set, sig);
7271 mask >>= 1;
7272 sig++;
7273 }
7274 sigdelset(&G.blocked_set, SIGCHLD);
7275
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007276 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7277 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7278
Denis Vlasenkof9375282009-04-05 19:13:39 +00007279 /* POSIX allows shell to re-enable SIGCHLD
7280 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007281#if ENABLE_HUSH_FAST
7282 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007283 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007284 signal(SIGCHLD, SIGCHLD_handler);
7285#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007286 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007287 signal(SIGCHLD, SIG_DFL);
7288#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007289
7290 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007291}
7292
7293#if ENABLE_HUSH_JOB
7294/* helper */
7295static void maybe_set_to_sigexit(int sig)
7296{
7297 void (*handler)(int);
7298 /* non_DFL_mask'ed signals are, well, masked,
7299 * no need to set handler for them.
7300 */
7301 if (!((G.non_DFL_mask >> sig) & 1)) {
7302 handler = signal(sig, sigexit);
7303 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7304 signal(sig, handler);
7305 }
7306}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007307/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007308static void set_fatal_handlers(void)
7309{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007310 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007311 if (HUSH_DEBUG) {
7312 maybe_set_to_sigexit(SIGILL );
7313 maybe_set_to_sigexit(SIGFPE );
7314 maybe_set_to_sigexit(SIGBUS );
7315 maybe_set_to_sigexit(SIGSEGV);
7316 maybe_set_to_sigexit(SIGTRAP);
7317 } /* else: hush is perfect. what SEGV? */
7318 maybe_set_to_sigexit(SIGABRT);
7319 /* bash 3.2 seems to handle these just like 'fatal' ones */
7320 maybe_set_to_sigexit(SIGPIPE);
7321 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007322 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007323 * if we aren't interactive... but in this case
7324 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007325 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007326 /*maybe_set_to_sigexit(SIGTERM);*/
7327 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007328}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007329#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007330
Denis Vlasenkod5762932009-03-31 11:22:57 +00007331static int set_mode(const char cstate, const char mode)
7332{
7333 int state = (cstate == '-' ? 1 : 0);
7334 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007335 case 'n': G.n_mode = state; break;
7336 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007337 default: return EXIT_FAILURE;
7338 }
7339 return EXIT_SUCCESS;
7340}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007341
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007342int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007343int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007344{
7345 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007346 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007347 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007348 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00007349
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007350 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007351 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007352 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007353#if !BB_MMU
7354 G.argv0_for_re_execing = argv[0];
7355#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007356 /* Deal with HUSH_VERSION */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007357 G.shell_ver.flg_export = 1;
7358 G.shell_ver.flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007359 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007360 * therefore we xstrdup: */
7361 G.shell_ver.varstr = xstrdup(hush_version_str),
Denis Vlasenko87a86552008-07-29 19:43:10 +00007362 G.top_var = &G.shell_ver;
Denys Vlasenko605067b2010-09-06 12:10:51 +02007363 /* Create shell local variables from the values
7364 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007365 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007366 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007367 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007368 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007369 if (e) while (*e) {
7370 char *value = strchr(*e, '=');
7371 if (value) { /* paranoia */
7372 cur_var->next = xzalloc(sizeof(*cur_var));
7373 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007374 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007375 cur_var->max_len = strlen(*e);
7376 cur_var->flg_export = 1;
7377 }
7378 e++;
7379 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007380 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7381 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7382 putenv(G.shell_ver.varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007383
7384 /* Export PWD */
7385 set_pwd_var(/*exp:*/ 1);
7386 /* bash also exports SHLVL and _,
7387 * and sets (but doesn't export) the following variables:
7388 * BASH=/bin/bash
7389 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7390 * BASH_VERSION='3.2.0(1)-release'
7391 * HOSTTYPE=i386
7392 * MACHTYPE=i386-pc-linux-gnu
7393 * OSTYPE=linux-gnu
7394 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007395 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007396 * EUID=<NNNNN>
7397 * UID=<NNNNN>
7398 * GROUPS=()
7399 * LINES=<NNN>
7400 * COLUMNS=<NNN>
7401 * BASH_ARGC=()
7402 * BASH_ARGV=()
7403 * BASH_LINENO=()
7404 * BASH_SOURCE=()
7405 * DIRSTACK=()
7406 * PIPESTATUS=([0]="0")
7407 * HISTFILE=/<xxx>/.bash_history
7408 * HISTFILESIZE=500
7409 * HISTSIZE=500
7410 * MAILCHECK=60
7411 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7412 * SHELL=/bin/bash
7413 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7414 * TERM=dumb
7415 * OPTERR=1
7416 * OPTIND=1
7417 * IFS=$' \t\n'
7418 * PS1='\s-\v\$ '
7419 * PS2='> '
7420 * PS4='+ '
7421 */
7422
Denis Vlasenko38f63192007-01-22 09:03:07 +00007423#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007424 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007425# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7426 {
7427 const char *hp = get_local_var_value("HISTFILE");
7428 if (!hp) {
7429 hp = get_local_var_value("HOME");
7430 if (hp) {
7431 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7432 //set_local_var(xasprintf("HISTFILE=%s", ...));
7433 }
7434 }
7435 }
7436# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007437#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007438
Denis Vlasenko87a86552008-07-29 19:43:10 +00007439 G.global_argc = argc;
7440 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007441 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007442 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007443
Denis Vlasenkoed782372009-04-10 00:45:02 +00007444 if (setjmp(die_jmp)) {
7445 /* xfunc has failed! die die die */
7446 /* no EXIT traps, this is an escape hatch! */
7447 G.exiting = 1;
7448 hush_exit(xfunc_error_retval);
7449 }
7450
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007451 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007452 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007453 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007454 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007455 * in order to intercept (more) signals.
7456 */
7457
7458 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007459 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007460 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007461 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007462 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007463#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007464 "<:$:R:V:"
7465# if ENABLE_HUSH_FUNCTIONS
7466 "F:"
7467# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007468#endif
7469 );
7470 if (opt <= 0)
7471 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007472 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007473 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007474 /* Possibilities:
7475 * sh ... -c 'script'
7476 * sh ... -c 'script' ARG0 [ARG1...]
7477 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007478 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007479 * "" needs to be replaced with NULL
7480 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007481 * Note: the form without ARG0 never happens:
7482 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007483 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007484 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007485 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007486 G.root_ppid = getppid();
7487 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007488 G.global_argv = argv + optind;
7489 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007490 if (builtin_argc) {
7491 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7492 const struct built_in_command *x;
7493
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007494 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007495 x = find_builtin(optarg);
7496 if (x) { /* paranoia */
7497 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7498 G.global_argv += builtin_argc;
7499 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007500 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007501 }
7502 goto final_return;
7503 }
7504 if (!G.global_argv[0]) {
7505 /* -c 'script' (no params): prevent empty $0 */
7506 G.global_argv--; /* points to argv[i] of 'script' */
7507 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007508 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007509 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007510 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007511 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007512 goto final_return;
7513 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007514 /* Well, we cannot just declare interactiveness,
7515 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007516 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007517 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007518 case 's':
7519 /* "-s" means "read from stdin", but this is how we always
7520 * operate, so simply do nothing here. */
7521 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007522#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007523 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007524 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007525 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007526 case '$': {
7527 unsigned long long empty_trap_mask;
7528
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007529 G.root_pid = bb_strtou(optarg, &optarg, 16);
7530 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007531 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7532 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007533 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7534 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007535 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007536 optarg++;
7537 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007538 optarg++;
7539 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7540 if (empty_trap_mask != 0) {
7541 int sig;
7542 init_sigmasks();
7543 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7544 for (sig = 1; sig < NSIG; sig++) {
7545 if (empty_trap_mask & (1LL << sig)) {
7546 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7547 sigaddset(&G.blocked_set, sig);
7548 }
7549 }
7550 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7551 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007552# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007553 optarg++;
7554 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007555# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007556 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007557 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007558 case 'R':
7559 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007560 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007561 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007562# if ENABLE_HUSH_FUNCTIONS
7563 case 'F': {
7564 struct function *funcp = new_function(optarg);
7565 /* funcp->name is already set to optarg */
7566 /* funcp->body is set to NULL. It's a special case. */
7567 funcp->body_as_string = argv[optind];
7568 optind++;
7569 break;
7570 }
7571# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007572#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007573 case 'n':
7574 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007575 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007576 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007577 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007578#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007579 fprintf(stderr, "Usage: sh [FILE]...\n"
7580 " or: sh -c command [args]...\n\n");
7581 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007582#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007583 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007584#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007585 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007586 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007587
Denys Vlasenkodea47882009-10-09 15:40:49 +02007588 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007589 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007590 G.root_ppid = getppid();
7591 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007592
7593 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007594 if (argv[0] && argv[0][0] == '-') {
7595 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007596 debug_printf("sourcing /etc/profile\n");
7597 input = fopen_for_read("/etc/profile");
7598 if (input != NULL) {
7599 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007600 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007601 parse_and_run_file(input);
7602 fclose(input);
7603 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007604 /* bash: after sourcing /etc/profile,
7605 * tries to source (in the given order):
7606 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007607 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007608 * bash also sources ~/.bash_logout on exit.
7609 * If called as sh, skips .bash_XXX files.
7610 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007611 }
7612
Denis Vlasenkof9375282009-04-05 19:13:39 +00007613 if (argv[optind]) {
7614 FILE *input;
7615 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007616 * "bash <script>" (which is never interactive (unless -i?))
7617 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007618 * If called as sh, does the same but with $ENV.
7619 */
7620 debug_printf("running script '%s'\n", argv[optind]);
7621 G.global_argv = argv + optind;
7622 G.global_argc = argc - optind;
7623 input = xfopen_for_read(argv[optind]);
7624 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007625 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007626 parse_and_run_file(input);
7627#if ENABLE_FEATURE_CLEAN_UP
7628 fclose(input);
7629#endif
7630 goto final_return;
7631 }
7632
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007633 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007634 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007635 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007636
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007637 /* A shell is interactive if the '-i' flag was given,
7638 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007639 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007640 * no arguments remaining or the -s flag given
7641 * standard input is a terminal
7642 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007643 * Refer to Posix.2, the description of the 'sh' utility.
7644 */
7645#if ENABLE_HUSH_JOB
7646 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007647 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7648 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7649 if (G_saved_tty_pgrp < 0)
7650 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007651
7652 /* try to dup stdin to high fd#, >= 255 */
7653 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7654 if (G_interactive_fd < 0) {
7655 /* try to dup to any fd */
7656 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007657 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007658 /* give up */
7659 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007660 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007661 }
7662 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007663// TODO: track & disallow any attempts of user
7664// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007665 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007666 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007667 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007668 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007669
Mike Frysinger38478a62009-05-20 04:48:06 -04007670 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007671 /* If we were run as 'hush &', sleep until we are
7672 * in the foreground (tty pgrp == our pgrp).
7673 * If we get started under a job aware app (like bash),
7674 * make sure we are now in charge so we don't fight over
7675 * who gets the foreground */
7676 while (1) {
7677 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007678 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7679 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007680 break;
7681 /* send TTIN to ourself (should stop us) */
7682 kill(- shell_pgrp, SIGTTIN);
7683 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007684 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007685
Denis Vlasenkof9375282009-04-05 19:13:39 +00007686 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007687 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007688
Mike Frysinger38478a62009-05-20 04:48:06 -04007689 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007690 /* Set other signals to restore saved_tty_pgrp */
7691 set_fatal_handlers();
7692 /* Put ourselves in our own process group
7693 * (bash, too, does this only if ctty is available) */
7694 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7695 /* Grab control of the terminal */
7696 tcsetpgrp(G_interactive_fd, getpid());
7697 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007698 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007699 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007700 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007701 } else {
7702 init_sigmasks();
7703 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007704#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007705 /* No job control compiled in, only prompt/line editing */
7706 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007707 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7708 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007709 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007710 G_interactive_fd = dup(STDIN_FILENO);
7711 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007712 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007713 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007714 }
7715 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007716 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007717 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007718 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007719 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007720#else
7721 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007722 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007723#endif
7724 /* bash:
7725 * if interactive but not a login shell, sources ~/.bashrc
7726 * (--norc turns this off, --rcfile <file> overrides)
7727 */
7728
7729 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007730 /* note: ash and hush share this string */
7731 printf("\n\n%s %s\n"
7732 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7733 "\n",
7734 bb_banner,
7735 "hush - the humble shell"
7736 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007737 }
7738
Denis Vlasenkof9375282009-04-05 19:13:39 +00007739 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007740
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007741 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007742#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007743 if (G.cwd != bb_msg_unknown)
7744 free((char*)G.cwd);
7745 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007746 while (cur_var) {
7747 struct variable *tmp = cur_var;
7748 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007749 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007750 cur_var = cur_var->next;
7751 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007752 }
Eric Andersen25f27032001-04-26 23:22:31 +00007753#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007754 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007755}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007756
7757
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007758#if ENABLE_MSH
7759int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7760int msh_main(int argc, char **argv)
7761{
7762 //bb_error_msg("msh is deprecated, please use hush instead");
7763 return hush_main(argc, argv);
7764}
7765#endif
7766
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007767
7768/*
7769 * Built-ins
7770 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007771static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007772{
7773 return 0;
7774}
7775
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007776static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007777{
7778 int argc = 0;
7779 while (*argv) {
7780 argc++;
7781 argv++;
7782 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007783 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007784}
7785
7786static int FAST_FUNC builtin_test(char **argv)
7787{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007788 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007789}
7790
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007791static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007792{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007793 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007794}
7795
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007796#if ENABLE_PRINTF
7797static int FAST_FUNC builtin_printf(char **argv)
7798{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007799 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007800}
7801#endif
7802
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007803static char **skip_dash_dash(char **argv)
7804{
7805 argv++;
7806 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7807 argv++;
7808 return argv;
7809}
7810
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007811static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007812{
7813 int rcode = EXIT_SUCCESS;
7814
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007815 argv = skip_dash_dash(argv);
7816 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007817 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007818 /* bash:
7819 * eval "echo Hi; done" ("done" is syntax error):
7820 * "echo Hi" will not execute too.
7821 */
7822 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007823 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007824 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007825 }
7826 return rcode;
7827}
7828
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007829static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007830{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007831 const char *newdir;
7832
7833 argv = skip_dash_dash(argv);
7834 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007835 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007836 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007837 * bash says "bash: cd: HOME not set" and does nothing
7838 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007839 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007840 const char *home = get_local_var_value("HOME");
7841 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007842 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007843 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007844 /* Mimic bash message exactly */
7845 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007846 return EXIT_FAILURE;
7847 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007848 /* Read current dir (get_cwd(1) is inside) and set PWD.
7849 * Note: do not enforce exporting. If PWD was unset or unexported,
7850 * set it again, but do not export. bash does the same.
7851 */
7852 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007853 return EXIT_SUCCESS;
7854}
7855
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007856static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007857{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007858 argv = skip_dash_dash(argv);
7859 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007860 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007861
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007862 /* Careful: we can end up here after [v]fork. Do not restore
7863 * tty pgrp then, only top-level shell process does that */
7864 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7865 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7866
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007867 /* TODO: if exec fails, bash does NOT exit! We do.
7868 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7869 * and tcsetpgrp, and this is inherently racy.
7870 */
7871 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007872}
7873
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007874static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007875{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007876 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007877
7878 /* interactive bash:
7879 * # trap "echo EEE" EXIT
7880 * # exit
7881 * exit
7882 * There are stopped jobs.
7883 * (if there are _stopped_ jobs, running ones don't count)
7884 * # exit
7885 * exit
7886 # EEE (then bash exits)
7887 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02007888 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00007889 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007890
7891 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007892 argv = skip_dash_dash(argv);
7893 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007894 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007895 /* mimic bash: exit 123abc == exit 255 + error msg */
7896 xfunc_error_retval = 255;
7897 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007898 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007899}
7900
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007901static void print_escaped(const char *s)
7902{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007903 if (*s == '\'')
7904 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007905 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007906 const char *p = strchrnul(s, '\'');
7907 /* print 'xxxx', possibly just '' */
7908 printf("'%.*s'", (int)(p - s), s);
7909 if (*p == '\0')
7910 break;
7911 s = p;
7912 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007913 /* s points to '; print "'''...'''" */
7914 putchar('"');
7915 do putchar('\''); while (*++s == '\'');
7916 putchar('"');
7917 } while (*s);
7918}
7919
Denys Vlasenko295fef82009-06-03 12:47:26 +02007920#if !ENABLE_HUSH_LOCAL
7921#define helper_export_local(argv, exp, lvl) \
7922 helper_export_local(argv, exp)
7923#endif
7924static void helper_export_local(char **argv, int exp, int lvl)
7925{
7926 do {
7927 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007928 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02007929
7930 /* So far we do not check that name is valid (TODO?) */
7931
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007932 if (*name_end == '\0') {
7933 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02007934
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007935 vpp = get_ptr_to_local_var(name, name_end - name);
7936 var = vpp ? *vpp : NULL;
7937
Denys Vlasenko295fef82009-06-03 12:47:26 +02007938 if (exp == -1) { /* unexporting? */
7939 /* export -n NAME (without =VALUE) */
7940 if (var) {
7941 var->flg_export = 0;
7942 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7943 unsetenv(name);
7944 } /* else: export -n NOT_EXISTING_VAR: no-op */
7945 continue;
7946 }
7947 if (exp == 1) { /* exporting? */
7948 /* export NAME (without =VALUE) */
7949 if (var) {
7950 var->flg_export = 1;
7951 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7952 putenv(var->varstr);
7953 continue;
7954 }
7955 }
7956 /* Exporting non-existing variable.
7957 * bash does not put it in environment,
7958 * but remembers that it is exported,
7959 * and does put it in env when it is set later.
7960 * We just set it to "" and export. */
7961 /* Or, it's "local NAME" (without =VALUE).
7962 * bash sets the value to "". */
7963 name = xasprintf("%s=", name);
7964 } else {
7965 /* (Un)exporting/making local NAME=VALUE */
7966 name = xstrdup(name);
7967 }
7968 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7969 } while (*++argv);
7970}
7971
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007972static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007973{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007974 unsigned opt_unexport;
7975
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007976#if ENABLE_HUSH_EXPORT_N
7977 /* "!": do not abort on errors */
7978 opt_unexport = getopt32(argv, "!n");
7979 if (opt_unexport == (uint32_t)-1)
7980 return EXIT_FAILURE;
7981 argv += optind;
7982#else
7983 opt_unexport = 0;
7984 argv++;
7985#endif
7986
7987 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007988 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007989 if (e) {
7990 while (*e) {
7991#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007992 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007993#else
7994 /* ash emits: export VAR='VAL'
7995 * bash: declare -x VAR="VAL"
7996 * we follow ash example */
7997 const char *s = *e++;
7998 const char *p = strchr(s, '=');
7999
8000 if (!p) /* wtf? take next variable */
8001 continue;
8002 /* export var= */
8003 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008004 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008005 putchar('\n');
8006#endif
8007 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008008 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008009 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008010 return EXIT_SUCCESS;
8011 }
8012
Denys Vlasenko295fef82009-06-03 12:47:26 +02008013 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008014
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008015 return EXIT_SUCCESS;
8016}
8017
Denys Vlasenko295fef82009-06-03 12:47:26 +02008018#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008019static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008020{
8021 if (G.func_nest_level == 0) {
8022 bb_error_msg("%s: not in a function", argv[0]);
8023 return EXIT_FAILURE; /* bash compat */
8024 }
8025 helper_export_local(argv, 0, G.func_nest_level);
8026 return EXIT_SUCCESS;
8027}
8028#endif
8029
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008030static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008031{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008032 int sig;
8033 char *new_cmd;
8034
8035 if (!G.traps)
8036 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8037
8038 argv++;
8039 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008040 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008041 /* No args: print all trapped */
8042 for (i = 0; i < NSIG; ++i) {
8043 if (G.traps[i]) {
8044 printf("trap -- ");
8045 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008046 /* note: bash adds "SIG", but only if invoked
8047 * as "bash". If called as "sh", or if set -o posix,
8048 * then it prints short signal names.
8049 * We are printing short names: */
8050 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008051 }
8052 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008053 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008054 return EXIT_SUCCESS;
8055 }
8056
8057 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008058 /* If first arg is a number: reset all specified signals */
8059 sig = bb_strtou(*argv, NULL, 10);
8060 if (errno == 0) {
8061 int ret;
8062 process_sig_list:
8063 ret = EXIT_SUCCESS;
8064 while (*argv) {
8065 sig = get_signum(*argv++);
8066 if (sig < 0 || sig >= NSIG) {
8067 ret = EXIT_FAILURE;
8068 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008069 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008070 continue;
8071 }
8072
8073 free(G.traps[sig]);
8074 G.traps[sig] = xstrdup(new_cmd);
8075
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008076 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008077 get_signame(sig), sig, G.traps[sig]);
8078
8079 /* There is no signal for 0 (EXIT) */
8080 if (sig == 0)
8081 continue;
8082
8083 if (new_cmd) {
8084 sigaddset(&G.blocked_set, sig);
8085 } else {
8086 /* There was a trap handler, we are removing it
8087 * (if sig has non-DFL handling,
8088 * we don't need to do anything) */
8089 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8090 continue;
8091 sigdelset(&G.blocked_set, sig);
8092 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008093 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008094 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008095 return ret;
8096 }
8097
8098 if (!argv[1]) { /* no second arg */
8099 bb_error_msg("trap: invalid arguments");
8100 return EXIT_FAILURE;
8101 }
8102
8103 /* First arg is "-": reset all specified to default */
8104 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8105 /* Everything else: set arg as signal handler
8106 * (includes "" case, which ignores signal) */
8107 if (argv[0][0] == '-') {
8108 if (argv[0][1] == '\0') { /* "-" */
8109 /* new_cmd remains NULL: "reset these sigs" */
8110 goto reset_traps;
8111 }
8112 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8113 argv++;
8114 }
8115 /* else: "-something", no special meaning */
8116 }
8117 new_cmd = *argv;
8118 reset_traps:
8119 argv++;
8120 goto process_sig_list;
8121}
8122
Mike Frysinger93cadc22009-05-27 17:06:25 -04008123/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008124static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008125{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008126 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008127
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008128 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008129 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008130 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008131
8132 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008133 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008134 type = "an alias";*/
8135#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008136 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008137 type = "a function";
8138#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008139 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008140 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008141 else if ((path = find_in_path(*argv)) != NULL)
8142 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008143 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008144 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008145 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008146 continue;
8147 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008148
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008149 printf("%s is %s\n", *argv, type);
8150 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008151 }
8152
8153 return ret;
8154}
8155
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008156#if ENABLE_HUSH_JOB
8157/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008158static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008159{
8160 int i, jobnum;
8161 struct pipe *pi;
8162
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008163 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008164 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008165
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008166 /* If they gave us no args, assume they want the last backgrounded task */
8167 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008168 for (pi = G.job_list; pi; pi = pi->next) {
8169 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008170 goto found;
8171 }
8172 }
8173 bb_error_msg("%s: no current job", argv[0]);
8174 return EXIT_FAILURE;
8175 }
8176 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8177 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8178 return EXIT_FAILURE;
8179 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008180 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008181 if (pi->jobid == jobnum) {
8182 goto found;
8183 }
8184 }
8185 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8186 return EXIT_FAILURE;
8187 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008188 /* TODO: bash prints a string representation
8189 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008190 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008191 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008192 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008193 }
8194
8195 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008196 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8197 for (i = 0; i < pi->num_cmds; i++) {
8198 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8199 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008200 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008201 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008202
8203 i = kill(- pi->pgrp, SIGCONT);
8204 if (i < 0) {
8205 if (errno == ESRCH) {
8206 delete_finished_bg_job(pi);
8207 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008208 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008209 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008210 }
8211
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008212 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008213 remove_bg_job(pi);
8214 return checkjobs_and_fg_shell(pi);
8215 }
8216 return EXIT_SUCCESS;
8217}
8218#endif
8219
8220#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008221static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008222{
8223 const struct built_in_command *x;
8224
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008225 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008226 "Built-in commands:\n"
8227 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008228 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008229 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008230 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008231 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008232 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008233 return EXIT_SUCCESS;
8234}
8235#endif
8236
8237#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008238static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008239{
8240 struct pipe *job;
8241 const char *status_string;
8242
Denis Vlasenko87a86552008-07-29 19:43:10 +00008243 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008244 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008245 status_string = "Stopped";
8246 else
8247 status_string = "Running";
8248
8249 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8250 }
8251 return EXIT_SUCCESS;
8252}
8253#endif
8254
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008255#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008256static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008257{
8258 void *p;
8259 unsigned long l;
8260
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008261# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008262 /* Optional. Reduces probability of false positives */
8263 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008264# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008265 /* Crude attempt to find where "free memory" starts,
8266 * sans fragmentation. */
8267 p = malloc(240);
8268 l = (unsigned long)p;
8269 free(p);
8270 p = malloc(3400);
8271 if (l < (unsigned long)p) l = (unsigned long)p;
8272 free(p);
8273
8274 if (!G.memleak_value)
8275 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008276
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008277 l -= G.memleak_value;
8278 if ((long)l < 0)
8279 l = 0;
8280 l /= 1024;
8281 if (l > 127)
8282 l = 127;
8283
8284 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8285 return l;
8286}
8287#endif
8288
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008289static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008290{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008291 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008292 return EXIT_SUCCESS;
8293}
8294
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008295static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008296{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008297 const char *r;
8298 char *opt_n = NULL;
8299 char *opt_p = NULL;
8300 char *opt_t = NULL;
8301 char *opt_u = NULL;
8302 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008303
Denys Vlasenko03dad222010-01-12 23:29:57 +01008304 /* "!": do not abort on errors.
8305 * Option string must start with "sr" to match BUILTIN_READ_xxx
8306 */
8307 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8308 if (read_flags == (uint32_t)-1)
8309 return EXIT_FAILURE;
8310 argv += optind;
8311
8312 r = shell_builtin_read(set_local_var_from_halves,
8313 argv,
8314 get_local_var_value("IFS"), /* can be NULL */
8315 read_flags,
8316 opt_n,
8317 opt_p,
8318 opt_t,
8319 opt_u
8320 );
8321
8322 if ((uintptr_t)r > 1) {
8323 bb_error_msg("%s", r);
8324 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008325 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008326
Denys Vlasenko03dad222010-01-12 23:29:57 +01008327 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008328}
8329
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008330/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8331 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008332 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008333 * set [-abCefhmnuvx] [-o option] [argument...]
8334 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008335 * set -- [argument...]
8336 * set -o
8337 * set +o
8338 * Implementations shall support the options in both their hyphen and
8339 * plus-sign forms. These options can also be specified as options to sh.
8340 * Examples:
8341 * Write out all variables and their values: set
8342 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8343 * Turn on the -x and -v options: set -xv
8344 * Unset all positional parameters: set --
8345 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8346 * Set the positional parameters to the expansion of x, even if x expands
8347 * with a leading '-' or '+': set -- $x
8348 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008349 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008350 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008351static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008352{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008353 int n;
8354 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008355 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008356
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008357 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008358 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008359 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008360 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008361 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008362 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008363
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008364 do {
8365 if (!strcmp(arg, "--")) {
8366 ++argv;
8367 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008368 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008369 if (arg[0] != '+' && arg[0] != '-')
8370 break;
8371 for (n = 1; arg[n]; ++n)
8372 if (set_mode(arg[0], arg[n]))
8373 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008374 } while ((arg = *++argv) != NULL);
8375 /* Now argv[0] is 1st argument */
8376
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008377 if (arg == NULL)
8378 return EXIT_SUCCESS;
8379 set_argv:
8380
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008381 /* NB: G.global_argv[0] ($0) is never freed/changed */
8382 g_argv = G.global_argv;
8383 if (G.global_args_malloced) {
8384 pp = g_argv;
8385 while (*++pp)
8386 free(*pp);
8387 g_argv[1] = NULL;
8388 } else {
8389 G.global_args_malloced = 1;
8390 pp = xzalloc(sizeof(pp[0]) * 2);
8391 pp[0] = g_argv[0]; /* retain $0 */
8392 g_argv = pp;
8393 }
8394 /* This realloc's G.global_argv */
8395 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8396
8397 n = 1;
8398 while (*++pp)
8399 n++;
8400 G.global_argc = n;
8401
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008402 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008403
8404 /* Nothing known, so abort */
8405 error:
8406 bb_error_msg("set: %s: invalid option", arg);
8407 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008408}
8409
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008410static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008411{
8412 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008413 argv = skip_dash_dash(argv);
8414 if (argv[0]) {
8415 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008416 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008417 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008418 if (G.global_args_malloced) {
8419 int m = 1;
8420 while (m <= n)
8421 free(G.global_argv[m++]);
8422 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008423 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008424 memmove(&G.global_argv[1], &G.global_argv[n+1],
8425 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008426 return EXIT_SUCCESS;
8427 }
8428 return EXIT_FAILURE;
8429}
8430
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008431static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008432{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008433 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008434 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008435 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008436#if ENABLE_HUSH_FUNCTIONS
8437 smallint sv_flg;
8438#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008439
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008440 argv = skip_dash_dash(argv);
8441 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008442 if (!filename) {
8443 /* bash says: "bash: .: filename argument required" */
8444 return 2; /* bash compat */
8445 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008446 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008447 if (!strchr(filename, '/')) {
8448 arg_path = find_in_path(filename);
8449 if (arg_path)
8450 filename = arg_path;
8451 }
8452 input = fopen_or_warn(filename, "r");
8453 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008454 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008455 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008456 return EXIT_FAILURE;
8457 }
8458 close_on_exec_on(fileno(input));
8459
Mike Frysinger885b6f22009-04-18 21:04:25 +00008460#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008461 sv_flg = G.flag_return_in_progress;
8462 /* "we are inside sourced file, ok to use return" */
8463 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008464#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008465 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008466
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008467 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008468 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008469
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008470 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008471#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008472 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008473#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008474
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008475 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008476}
8477
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008478static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008479{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008480 int rc;
8481 mode_t mask;
8482
8483 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008484 argv = skip_dash_dash(argv);
8485 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008486 mode_t old_mask = mask;
8487
8488 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008489 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008490 mask ^= 0777;
8491 if (rc == 0) {
8492 mask = old_mask;
8493 /* bash messages:
8494 * bash: umask: 'q': invalid symbolic mode operator
8495 * bash: umask: 999: octal number out of range
8496 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008497 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008498 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008499 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008500 rc = 1;
8501 /* Mimic bash */
8502 printf("%04o\n", (unsigned) mask);
8503 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008504 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008505 umask(mask);
8506
8507 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008508}
8509
Mike Frysingerd690f682009-03-30 06:50:54 +00008510/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008511static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008512{
Mike Frysingerd690f682009-03-30 06:50:54 +00008513 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008514 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008515
Denis Vlasenko28e67962009-04-26 23:22:40 +00008516 /* "!": do not abort on errors */
8517 /* "+": stop at 1st non-option */
8518 opts = getopt32(argv, "!+vf");
8519 if (opts == (unsigned)-1)
8520 return EXIT_FAILURE;
8521 if (opts == 3) {
8522 bb_error_msg("unset: -v and -f are exclusive");
8523 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008524 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008525 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008526
8527 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008528 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008529 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008530 if (unset_local_var(*argv)) {
8531 /* unset <nonexistent_var> doesn't fail.
8532 * Error is when one tries to unset RO var.
8533 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008534 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008535 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008536 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008537#if ENABLE_HUSH_FUNCTIONS
8538 else {
8539 unset_func(*argv);
8540 }
8541#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008542 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008543 }
8544 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008545}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008546
Mike Frysinger56bdea12009-03-28 20:01:58 +00008547/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008548static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008549{
8550 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008551 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008552
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008553 argv = skip_dash_dash(argv);
8554 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008555 /* Don't care about wait results */
8556 /* Note 1: must wait until there are no more children */
8557 /* Note 2: must be interruptible */
8558 /* Examples:
8559 * $ sleep 3 & sleep 6 & wait
8560 * [1] 30934 sleep 3
8561 * [2] 30935 sleep 6
8562 * [1] Done sleep 3
8563 * [2] Done sleep 6
8564 * $ sleep 3 & sleep 6 & wait
8565 * [1] 30936 sleep 3
8566 * [2] 30937 sleep 6
8567 * [1] Done sleep 3
8568 * ^C <-- after ~4 sec from keyboard
8569 * $
8570 */
8571 sigaddset(&G.blocked_set, SIGCHLD);
8572 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8573 while (1) {
8574 checkjobs(NULL);
8575 if (errno == ECHILD)
8576 break;
8577 /* Wait for SIGCHLD or any other signal of interest */
8578 /* sigtimedwait with infinite timeout: */
8579 sig = sigwaitinfo(&G.blocked_set, NULL);
8580 if (sig > 0) {
8581 sig = check_and_run_traps(sig);
8582 if (sig && sig != SIGCHLD) { /* see note 2 */
8583 ret = 128 + sig;
8584 break;
8585 }
8586 }
8587 }
8588 sigdelset(&G.blocked_set, SIGCHLD);
8589 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8590 return ret;
8591 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008592
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008593 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008594 while (*argv) {
8595 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008596 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008597 /* mimic bash message */
8598 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008599 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008600 }
8601 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008602 if (WIFSIGNALED(status))
8603 ret = 128 + WTERMSIG(status);
8604 else if (WIFEXITED(status))
8605 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008606 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008607 ret = EXIT_FAILURE;
8608 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008609 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008610 ret = 127;
8611 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008612 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008613 }
8614
8615 return ret;
8616}
8617
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008618#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8619static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8620{
8621 if (argv[1]) {
8622 def = bb_strtou(argv[1], NULL, 10);
8623 if (errno || def < def_min || argv[2]) {
8624 bb_error_msg("%s: bad arguments", argv[0]);
8625 def = UINT_MAX;
8626 }
8627 }
8628 return def;
8629}
8630#endif
8631
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008632#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008633static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008634{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008635 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008636 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008637 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008638 return EXIT_SUCCESS; /* bash compat */
8639 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008640 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008641
8642 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8643 if (depth == UINT_MAX)
8644 G.flag_break_continue = BC_BREAK;
8645 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008646 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008647
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008648 return EXIT_SUCCESS;
8649}
8650
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008651static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008652{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008653 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8654 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008655}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008656#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008657
8658#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008659static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008660{
8661 int rc;
8662
8663 if (G.flag_return_in_progress != -1) {
8664 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8665 return EXIT_FAILURE; /* bash compat */
8666 }
8667
8668 G.flag_return_in_progress = 1;
8669
8670 /* bash:
8671 * out of range: wraps around at 256, does not error out
8672 * non-numeric param:
8673 * f() { false; return qwe; }; f; echo $?
8674 * bash: return: qwe: numeric argument required <== we do this
8675 * 255 <== we also do this
8676 */
8677 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8678 return rc;
8679}
8680#endif