blob: b01f90370da304837d7a2afde88328081ef31639 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
11 * Credits:
12 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000013 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000016 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000017 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
21 * rewrites.
22 *
Eric Andersen25f27032001-04-26 23:22:31 +000023 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000024 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000025 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000026 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000028 *
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
39 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020040 * TODOs:
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
43 * tilde expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000044 * aliases
Denys Vlasenko349ef962010-05-21 15:46:24 +020045 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020048 * make complex ${var%...} constructs support optional
49 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000050 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020051 * Bash compat TODO:
52 * redirection of stdout+stderr: &> and >&
53 * brace expansion: one/{two,three,four}
54 * reserved words: function select
55 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020056 * process substitution: <(list) and >(list)
57 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020058 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020059 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
60 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
61 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020062 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020063 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
64 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko08218012009-06-03 14:43:56 +020066 * export builtin should be special, its arguments are assignments
67 * and therefore expansion of them should be "one-word" expansion:
68 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
69 * compare with:
70 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
71 * ls: cannot access i=a: No such file or directory
72 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020073 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020074 * Note2: bash 3.2.33(1) does this only if export word itself
75 * is not quoted:
76 * $ export i=`echo 'aaa bbb'`; echo "$i"
77 * aaa bbb
78 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
79 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000080 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +020081 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
Eric Andersen25f27032001-04-26 23:22:31 +000082 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020083#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denys Vlasenko27726cb2009-09-12 14:48:33 +020084#include <malloc.h> /* for malloc_trim */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000085#include <glob.h>
86/* #include <dmalloc.h> */
87#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000088# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000089#endif
Denys Vlasenko03dad222010-01-12 23:29:57 +010090
91#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000092#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000093#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +020094#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +020095# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +020096#else
97# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +020098#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000099#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200100# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000101#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000102
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
104//applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
106//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
107
108//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
109//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
110
111//config:config HUSH
112//config: bool "hush"
113//config: default y
114//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200115//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200116//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
117//config: case/esac. Redirections, here documents, $((arithmetic))
118//config: and functions are supported.
119//config:
120//config: It will compile and work on no-mmu systems.
121//config:
122//config: It does not handle select, aliases, brace expansion,
123//config: tilde expansion, &>file and >&file redirection of stdout+stderr.
124//config:
125//config:config HUSH_BASH_COMPAT
126//config: bool "bash-compatible extensions"
127//config: default y
128//config: depends on HUSH
129//config: help
130//config: Enable bash-compatible extensions.
131//config:
132//config:config HUSH_HELP
133//config: bool "help builtin"
134//config: default y
135//config: depends on HUSH
136//config: help
137//config: Enable help builtin in hush. Code size + ~1 kbyte.
138//config:
139//config:config HUSH_INTERACTIVE
140//config: bool "Interactive mode"
141//config: default y
142//config: depends on HUSH
143//config: help
144//config: Enable interactive mode (prompt and command editing).
145//config: Without this, hush simply reads and executes commands
146//config: from stdin just like a shell script from a file.
147//config: No prompt, no PS1/PS2 magic shell variables.
148//config:
149//config:config HUSH_JOB
150//config: bool "Job control"
151//config: default y
152//config: depends on HUSH_INTERACTIVE
153//config: help
154//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
155//config: command (not entire shell), fg/bg builtins work. Without this option,
156//config: "cmd &" still works by simply spawning a process and immediately
157//config: prompting for next command (or executing next command in a script),
158//config: but no separate process group is formed.
159//config:
160//config:config HUSH_TICK
161//config: bool "Process substitution"
162//config: default y
163//config: depends on HUSH
164//config: help
165//config: Enable process substitution `command` and $(command) in hush.
166//config:
167//config:config HUSH_IF
168//config: bool "Support if/then/elif/else/fi"
169//config: default y
170//config: depends on HUSH
171//config: help
172//config: Enable if/then/elif/else/fi in hush.
173//config:
174//config:config HUSH_LOOPS
175//config: bool "Support for, while and until loops"
176//config: default y
177//config: depends on HUSH
178//config: help
179//config: Enable for, while and until loops in hush.
180//config:
181//config:config HUSH_CASE
182//config: bool "Support case ... esac statement"
183//config: default y
184//config: depends on HUSH
185//config: help
186//config: Enable case ... esac statement in hush. +400 bytes.
187//config:
188//config:config HUSH_FUNCTIONS
189//config: bool "Support funcname() { commands; } syntax"
190//config: default y
191//config: depends on HUSH
192//config: help
193//config: Enable support for shell functions in hush. +800 bytes.
194//config:
195//config:config HUSH_LOCAL
196//config: bool "Support local builtin"
197//config: default y
198//config: depends on HUSH_FUNCTIONS
199//config: help
200//config: Enable support for local variables in functions.
201//config:
202//config:config HUSH_RANDOM_SUPPORT
203//config: bool "Pseudorandom generator and $RANDOM variable"
204//config: default y
205//config: depends on HUSH
206//config: help
207//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
208//config: Each read of "$RANDOM" will generate a new pseudorandom value.
209//config:
210//config:config HUSH_EXPORT_N
211//config: bool "Support 'export -n' option"
212//config: default y
213//config: depends on HUSH
214//config: help
215//config: export -n unexports variables. It is a bash extension.
216//config:
217//config:config HUSH_MODE_X
218//config: bool "Support 'hush -x' option and 'set -x' command"
219//config: default y
220//config: depends on HUSH
221//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200222//config: This instructs hush to print commands before execution.
223//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200224//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200225//config:config MSH
226//config: bool "msh (deprecated: aliased to hush)"
227//config: default n
228//config: select HUSH
229//config: help
230//config: msh is deprecated and will be removed, please migrate to hush.
231//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200232
233//usage:#define hush_trivial_usage NOUSAGE_STR
234//usage:#define hush_full_usage ""
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200235//usage:#define msh_trivial_usage NOUSAGE_STR
236//usage:#define msh_full_usage ""
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +0200237//usage:#define sh_trivial_usage NOUSAGE_STR
238//usage:#define sh_full_usage ""
239//usage:#define bash_trivial_usage NOUSAGE_STR
240//usage:#define bash_full_usage ""
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200241
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000242
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200243/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000244#define LEAK_HUNTING 0
245#define BUILD_AS_NOMMU 0
246/* Enable/disable sanity checks. Ok to enable in production,
247 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
248 * Keeping 1 for now even in released versions.
249 */
250#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200251/* Slightly bigger (+200 bytes), but faster hush.
252 * So far it only enables a trick with counting SIGCHLDs and forks,
253 * which allows us to do fewer waitpid's.
254 * (we can detect a case where neither forks were done nor SIGCHLDs happened
255 * and therefore waitpid will return the same result as last time)
256 */
257#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200258/* TODO: implement simplified code for users which do not need ${var%...} ops
259 * So far ${var%...} ops are always enabled:
260 */
261#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000262
263
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000264#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000265# undef BB_MMU
266# undef USE_FOR_NOMMU
267# undef USE_FOR_MMU
268# define BB_MMU 0
269# define USE_FOR_NOMMU(...) __VA_ARGS__
270# define USE_FOR_MMU(...)
271#endif
272
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200273#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100274#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000275/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000276# undef CONFIG_FEATURE_SH_STANDALONE
277# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000278# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100279# undef IF_NOT_FEATURE_SH_STANDALONE
280# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000281# define IF_FEATURE_SH_STANDALONE(...)
282# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000283#endif
284
Denis Vlasenko05743d72008-02-10 12:10:08 +0000285#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000286# undef ENABLE_FEATURE_EDITING
287# define ENABLE_FEATURE_EDITING 0
288# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
289# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000290#endif
291
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000292/* Do we support ANY keywords? */
293#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000294# define HAS_KEYWORDS 1
295# define IF_HAS_KEYWORDS(...) __VA_ARGS__
296# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000297#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000298# define HAS_KEYWORDS 0
299# define IF_HAS_KEYWORDS(...)
300# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000301#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000302
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000303/* If you comment out one of these below, it will be #defined later
304 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000305#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000306/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000307#define debug_printf_parse(...) do {} while (0)
308#define debug_print_tree(a, b) do {} while (0)
309#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000310#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000311#define debug_printf_jobs(...) do {} while (0)
312#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200313#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000314#define debug_printf_glob(...) do {} while (0)
315#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000316#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000317#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000318
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000319#define ERR_PTR ((void*)(long)1)
320
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200321#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000322
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200323#define _SPECIAL_VARS_STR "_*@$!?#"
324#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
325#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200326#if ENABLE_HUSH_BASH_COMPAT
327/* Support / and // replace ops */
328/* Note that // is stored as \ in "encoded" string representation */
329# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
330# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
331# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
332#else
333# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
334# define VAR_SUBST_OPS "%#:-=+?"
335# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
336#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200337
338#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000339
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200340struct variable;
341
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000342static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
343
344/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000345 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000346 */
347#if !BB_MMU
348typedef struct nommu_save_t {
349 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200350 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000351 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000352 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000353} nommu_save_t;
354#endif
355
Denys Vlasenko9b782552010-09-08 13:33:26 +0200356enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000357 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000358#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000359 RES_IF ,
360 RES_THEN ,
361 RES_ELIF ,
362 RES_ELSE ,
363 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000364#endif
365#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000366 RES_FOR ,
367 RES_WHILE ,
368 RES_UNTIL ,
369 RES_DO ,
370 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000371#endif
372#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000373 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000374#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000375#if ENABLE_HUSH_CASE
376 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200377 /* three pseudo-keywords support contrived "case" syntax: */
378 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
379 RES_MATCH , /* "word)" */
380 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000381 RES_ESAC ,
382#endif
383 RES_XXXX ,
384 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200385};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000386
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200387enum {
388 EXP_FLAG_GLOB = 0x200,
389 EXP_FLAG_ESC_GLOB_CHARS = 0x100,
390 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
391};
392
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000393typedef struct o_string {
394 char *data;
395 int length; /* position where data is appended */
396 int maxlen;
397 /* Protect newly added chars against globbing
398 * (by prepending \ to *, ?, [, \) */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200399 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000400 /* At least some part of the string was inside '' or "",
401 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200402 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000403 smallint has_empty_slot;
404 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
405} o_string;
406enum {
407 MAYBE_ASSIGNMENT = 0,
408 DEFINITELY_ASSIGNMENT = 1,
409 NOT_ASSIGNMENT = 2,
410 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
411};
412/* Used for initialization: o_string foo = NULL_O_STRING; */
413#define NULL_O_STRING { NULL }
414
415/* I can almost use ordinary FILE*. Is open_memstream() universally
416 * available? Where is it documented? */
417typedef struct in_str {
418 const char *p;
419 /* eof_flag=1: last char in ->p is really an EOF */
420 char eof_flag; /* meaningless if ->p == NULL */
421 char peek_buf[2];
422#if ENABLE_HUSH_INTERACTIVE
423 smallint promptme;
424 smallint promptmode; /* 0: PS1, 1: PS2 */
425#endif
426 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200427 int (*get) (struct in_str *) FAST_FUNC;
428 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000429} in_str;
430#define i_getch(input) ((input)->get(input))
431#define i_peek(input) ((input)->peek(input))
432
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200433/* The descrip member of this structure is only used to make
434 * debugging output pretty */
435static const struct {
436 int mode;
437 signed char default_fd;
438 char descrip[3];
439} redir_table[] = {
440 { O_RDONLY, 0, "<" },
441 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
442 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
443 { O_CREAT|O_RDWR, 1, "<>" },
444 { O_RDONLY, 0, "<<" },
445/* Should not be needed. Bogus default_fd helps in debugging */
446/* { O_RDONLY, 77, "<<" }, */
447};
448
Eric Andersen25f27032001-04-26 23:22:31 +0000449struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000450 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000451 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000452 int rd_fd; /* fd to redirect */
453 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
454 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000455 smallint rd_type; /* (enum redir_type) */
456 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000457 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200458 * bit 0: do we need to trim leading tabs?
459 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000460 */
Eric Andersen25f27032001-04-26 23:22:31 +0000461};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000462typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200463 REDIRECT_INPUT = 0,
464 REDIRECT_OVERWRITE = 1,
465 REDIRECT_APPEND = 2,
466 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000467 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200468 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000469
470 REDIRFD_CLOSE = -3,
471 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000472 REDIRFD_TO_FILE = -1,
473 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000474
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000475 HEREDOC_SKIPTABS = 1,
476 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000477} redir_type;
478
Eric Andersen25f27032001-04-26 23:22:31 +0000479
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000480struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000481 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000482 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000483 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200484 smallint cmd_type; /* CMD_xxx */
485#define CMD_NORMAL 0
486#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200487#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200488/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200489# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000490#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200491#if ENABLE_HUSH_FUNCTIONS
492# define CMD_FUNCDEF 3
493#endif
494
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200495 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
496 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000497#if !BB_MMU
498 char *group_as_string;
499#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000500#if ENABLE_HUSH_FUNCTIONS
501 struct function *child_func;
502/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200503 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000504 * When we execute "f1() {a;}" cmd, we create new function and clear
505 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200506 * When we execute "f1() {b;}", we notice that f1 exists,
507 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000508 * we put those fields back into cmd->xxx
509 * (struct function has ->parent_cmd ptr to facilitate that).
510 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
511 * Without this trick, loop would execute a;b;b;b;...
512 * instead of correct sequence a;b;a;b;...
513 * When command is freed, it severs the link
514 * (sets ->child_func->parent_cmd to NULL).
515 */
516#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000517 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000518/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
519 * and on execution these are substituted with their values.
520 * Substitution can make _several_ words out of one argv[n]!
521 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000522 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000523 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000524 struct redir_struct *redirects; /* I/O redirections */
525};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000526/* Is there anything in this command at all? */
527#define IS_NULL_CMD(cmd) \
528 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
529
Eric Andersen25f27032001-04-26 23:22:31 +0000530
531struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000532 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000533 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000534 int alive_cmds; /* number of commands running (not exited) */
535 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000536#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000537 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000538 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000539 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000540#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000541 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000542 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000543 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
544 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000545};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000546typedef enum pipe_style {
547 PIPE_SEQ = 1,
548 PIPE_AND = 2,
549 PIPE_OR = 3,
550 PIPE_BG = 4,
551} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000552/* Is there anything in this pipe at all? */
553#define IS_NULL_PIPE(pi) \
554 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000555
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000556/* This holds pointers to the various results of parsing */
557struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000558 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000559 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000560 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000561 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000562 /* last command in pipe (being constructed right now) */
563 struct command *command;
564 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000565 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000566#if !BB_MMU
567 o_string as_string;
568#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000569#if HAS_KEYWORDS
570 smallint ctx_res_w;
571 smallint ctx_inverted; /* "! cmd | cmd" */
572#if ENABLE_HUSH_CASE
573 smallint ctx_dsemicolon; /* ";;" seen */
574#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000575 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
576 int old_flag;
577 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000578 * example: "if pipe1; pipe2; then pipe3; fi"
579 * when we see "if" or "then", we malloc and copy current context,
580 * and make ->stack point to it. then we parse pipeN.
581 * when closing "then" / fi" / whatever is found,
582 * we move list_head into ->stack->command->group,
583 * copy ->stack into current context, and delete ->stack.
584 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000585 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000586 struct parse_context *stack;
587#endif
588};
589
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000590/* On program start, environ points to initial environment.
591 * putenv adds new pointers into it, unsetenv removes them.
592 * Neither of these (de)allocates the strings.
593 * setenv allocates new strings in malloc space and does putenv,
594 * and thus setenv is unusable (leaky) for shell's purposes */
595#define setenv(...) setenv_is_leaky_dont_use()
596struct variable {
597 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000598 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200599#if ENABLE_HUSH_LOCAL
600 unsigned func_nest_level;
601#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000602 int max_len; /* if > 0, name is part of initial env; else name is malloced */
603 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000604 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000605};
606
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000607enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000608 BC_BREAK = 1,
609 BC_CONTINUE = 2,
610};
611
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000612#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000613struct function {
614 struct function *next;
615 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000616 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000617 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200618# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000619 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200620# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000621};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000622#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000623
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000624
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000625/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000626/* Sorted roughly by size (smaller offsets == smaller code) */
627struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000628 /* interactive_fd != 0 means we are an interactive shell.
629 * If we are, then saved_tty_pgrp can also be != 0, meaning
630 * that controlling tty is available. With saved_tty_pgrp == 0,
631 * job control still works, but terminal signals
632 * (^C, ^Z, ^Y, ^\) won't work at all, and background
633 * process groups can only be created with "cmd &".
634 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
635 * to give tty to the foreground process group,
636 * and will take it back when the group is stopped (^Z)
637 * or killed (^C).
638 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000639#if ENABLE_HUSH_INTERACTIVE
640 /* 'interactive_fd' is a fd# open to ctty, if we have one
641 * _AND_ if we decided to act interactively */
642 int interactive_fd;
643 const char *PS1;
644 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000645# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000646#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000647# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000648#endif
649#if ENABLE_FEATURE_EDITING
650 line_input_t *line_input_state;
651#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000652 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200653 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000654 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200655#if ENABLE_HUSH_RANDOM_SUPPORT
656 random_t random_gen;
657#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000658#if ENABLE_HUSH_JOB
659 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000660 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000661 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000662 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400663# define G_saved_tty_pgrp (G.saved_tty_pgrp)
664#else
665# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000666#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000667 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000668#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000669 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000670#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000671#if ENABLE_HUSH_FUNCTIONS
672 /* 0: outside of a function (or sourced file)
673 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000674 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000675 */
676 smallint flag_return_in_progress;
677#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200678 smallint n_mode;
679#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200680 smallint x_mode;
Denys Vlasenko29082232010-07-16 13:52:32 +0200681# define G_x_mode (G.x_mode)
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200682#else
683# define G_x_mode 0
684#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000685 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000686 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000687 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000688 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000689 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100690 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000691 /* how many non-NULL argv's we have. NB: $# + 1 */
692 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000693 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000694#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000695 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000696#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000697#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000698 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000699 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000700#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000701 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000702 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000703 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000704 struct variable shell_ver;
Denys Vlasenko29082232010-07-16 13:52:32 +0200705 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000706#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000707 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200708# if ENABLE_HUSH_LOCAL
709 struct variable **shadowed_vars_pp;
710 unsigned func_nest_level;
711# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000712#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000713 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200714#if ENABLE_HUSH_FAST
715 unsigned count_SIGCHLD;
716 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200717 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200718#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000719 /* which signals have non-DFL handler (even with no traps set)? */
720 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000721 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000722 sigset_t blocked_set;
723 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000724#if HUSH_DEBUG
725 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000726 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000727#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200728 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000729};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000730#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000731/* Not #defining name to G.name - this quickly gets unwieldy
732 * (too many defines). Also, I actually prefer to see when a variable
733 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000734#define INIT_G() do { \
735 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
736} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000737
738
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000739/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200740static int builtin_cd(char **argv) FAST_FUNC;
741static int builtin_echo(char **argv) FAST_FUNC;
742static int builtin_eval(char **argv) FAST_FUNC;
743static int builtin_exec(char **argv) FAST_FUNC;
744static int builtin_exit(char **argv) FAST_FUNC;
745static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000746#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200747static int builtin_fg_bg(char **argv) FAST_FUNC;
748static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000749#endif
750#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200751static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000752#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200753#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200754static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200755#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000756#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200757static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000758#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400759#if ENABLE_PRINTF
760static int builtin_printf(char **argv) FAST_FUNC;
761#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200762static int builtin_pwd(char **argv) FAST_FUNC;
763static int builtin_read(char **argv) FAST_FUNC;
764static int builtin_set(char **argv) FAST_FUNC;
765static int builtin_shift(char **argv) FAST_FUNC;
766static int builtin_source(char **argv) FAST_FUNC;
767static int builtin_test(char **argv) FAST_FUNC;
768static int builtin_trap(char **argv) FAST_FUNC;
769static int builtin_type(char **argv) FAST_FUNC;
770static int builtin_true(char **argv) FAST_FUNC;
771static int builtin_umask(char **argv) FAST_FUNC;
772static int builtin_unset(char **argv) FAST_FUNC;
773static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000774#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200775static int builtin_break(char **argv) FAST_FUNC;
776static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000777#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000778#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200779static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000780#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000781
782/* Table of built-in functions. They can be forked or not, depending on
783 * context: within pipes, they fork. As simple commands, they do not.
784 * When used in non-forking context, they can change global variables
785 * in the parent shell process. If forked, of course they cannot.
786 * For example, 'unset foo | whatever' will parse and run, but foo will
787 * still be set at the end. */
788struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100789 const char *b_cmd;
790 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000791#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100792 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200793# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000794#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200795# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000796#endif
797};
798
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200799static const struct built_in_command bltins1[] = {
800 BLTIN("." , builtin_source , "Run commands in a file"),
801 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000802#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200803 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000804#endif
805#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200806 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000807#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200808 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000809#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200810 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000811#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200812 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
813 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
814 BLTIN("exit" , builtin_exit , "Exit"),
815 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000816#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200817 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000818#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000819#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200820 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000821#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000822#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200823 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000824#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200825#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200826 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200827#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000828#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200829 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000830#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200831 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000832#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200833 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000834#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200835 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
836 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200837#if ENABLE_HUSH_BASH_COMPAT
838 BLTIN("source" , builtin_source , "Run commands in a file"),
839#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200840 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100841 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100842 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200843 BLTIN("umask" , builtin_umask , "Set file creation mask"),
844 BLTIN("unset" , builtin_unset , "Unset variables"),
845 BLTIN("wait" , builtin_wait , "Wait for process"),
846};
847/* For now, echo and test are unconditionally enabled.
848 * Maybe make it configurable? */
849static const struct built_in_command bltins2[] = {
850 BLTIN("[" , builtin_test , NULL),
851 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400852#if ENABLE_PRINTF
853 BLTIN("printf" , builtin_printf , NULL),
854#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200855 BLTIN("pwd" , builtin_pwd , NULL),
856 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000857};
858
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000859
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000860/* Debug printouts.
861 */
862#if HUSH_DEBUG
863/* prevent disasters with G.debug_indent < 0 */
864# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
865# define debug_enter() (G.debug_indent++)
866# define debug_leave() (G.debug_indent--)
867#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200868# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000869# define debug_enter() ((void)0)
870# define debug_leave() ((void)0)
871#endif
872
873#ifndef debug_printf
874# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
875#endif
876
877#ifndef debug_printf_parse
878# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
879#endif
880
881#ifndef debug_printf_exec
882#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
883#endif
884
885#ifndef debug_printf_env
886# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
887#endif
888
889#ifndef debug_printf_jobs
890# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
891# define DEBUG_JOBS 1
892#else
893# define DEBUG_JOBS 0
894#endif
895
896#ifndef debug_printf_expand
897# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
898# define DEBUG_EXPAND 1
899#else
900# define DEBUG_EXPAND 0
901#endif
902
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200903#ifndef debug_printf_varexp
904# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
905#endif
906
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000907#ifndef debug_printf_glob
908# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
909# define DEBUG_GLOB 1
910#else
911# define DEBUG_GLOB 0
912#endif
913
914#ifndef debug_printf_list
915# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
916#endif
917
918#ifndef debug_printf_subst
919# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
920#endif
921
922#ifndef debug_printf_clean
923# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
924# define DEBUG_CLEAN 1
925#else
926# define DEBUG_CLEAN 0
927#endif
928
929#if DEBUG_EXPAND
930static void debug_print_strings(const char *prefix, char **vv)
931{
932 indent();
933 fprintf(stderr, "%s:\n", prefix);
934 while (*vv)
935 fprintf(stderr, " '%s'\n", *vv++);
936}
937#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200938# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000939#endif
940
941
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000942/* Leak hunting. Use hush_leaktool.sh for post-processing.
943 */
944#if LEAK_HUNTING
945static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000946{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000947 void *ptr = xmalloc((size + 0xff) & ~0xff);
948 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
949 return ptr;
950}
951static void *xxrealloc(int lineno, void *ptr, size_t size)
952{
953 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
954 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
955 return ptr;
956}
957static char *xxstrdup(int lineno, const char *str)
958{
959 char *ptr = xstrdup(str);
960 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
961 return ptr;
962}
963static void xxfree(void *ptr)
964{
965 fdprintf(2, "free %p\n", ptr);
966 free(ptr);
967}
Denys Vlasenko8391c482010-05-22 17:50:43 +0200968# define xmalloc(s) xxmalloc(__LINE__, s)
969# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
970# define xstrdup(s) xxstrdup(__LINE__, s)
971# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000972#endif
973
974
975/* Syntax and runtime errors. They always abort scripts.
976 * In interactive use they usually discard unparsed and/or unexecuted commands
977 * and return to the prompt.
978 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
979 */
980#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200981# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000982# define syntax_error(lineno, msg) syntax_error(msg)
983# define syntax_error_at(lineno, msg) syntax_error_at(msg)
984# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
985# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
986# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000987#endif
988
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000989static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000990{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000991 va_list p;
992
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000993#if HUSH_DEBUG >= 2
994 bb_error_msg("hush.c:%u", lineno);
995#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000996 va_start(p, fmt);
997 bb_verror_msg(fmt, p, NULL);
998 va_end(p);
999 if (!G_interactive_fd)
1000 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001001}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001002
1003static void syntax_error(unsigned lineno, const char *msg)
1004{
1005 if (msg)
1006 die_if_script(lineno, "syntax error: %s", msg);
1007 else
1008 die_if_script(lineno, "syntax error", NULL);
1009}
1010
1011static void syntax_error_at(unsigned lineno, const char *msg)
1012{
1013 die_if_script(lineno, "syntax error at '%s'", msg);
1014}
1015
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001016static void syntax_error_unterm_str(unsigned lineno, const char *s)
1017{
1018 die_if_script(lineno, "syntax error: unterminated %s", s);
1019}
1020
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001021/* It so happens that all such cases are totally fatal
1022 * even if shell is interactive: EOF while looking for closing
1023 * delimiter. There is nowhere to read stuff from after that,
1024 * it's EOF! The only choice is to terminate.
1025 */
1026static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001027static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001028{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001029 char msg[2] = { ch, '\0' };
1030 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001031 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001032}
1033
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001034static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001035{
1036 char msg[2];
1037 msg[0] = ch;
1038 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001039 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001040}
1041
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001042#if HUSH_DEBUG < 2
1043# undef die_if_script
1044# undef syntax_error
1045# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001046# undef syntax_error_unterm_ch
1047# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001048# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001049#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001050# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001051# define syntax_error(msg) syntax_error(__LINE__, msg)
1052# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1053# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1054# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1055# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001056#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001057
Denis Vlasenko552433b2009-04-04 19:29:21 +00001058
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001059#if ENABLE_HUSH_INTERACTIVE
1060static void cmdedit_update_prompt(void);
1061#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001062# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001063#endif
1064
1065
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001066/* Utility functions
1067 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001068/* Replace each \x with x in place, return ptr past NUL. */
1069static char *unbackslash(char *src)
1070{
Denys Vlasenko71885402009-09-24 01:44:13 +02001071 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001072 while (1) {
1073 if (*src == '\\')
1074 src++;
1075 if ((*dst++ = *src++) == '\0')
1076 break;
1077 }
1078 return dst;
1079}
1080
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001081static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001082{
1083 int i;
1084 unsigned count1;
1085 unsigned count2;
1086 char **v;
1087
1088 v = strings;
1089 count1 = 0;
1090 if (v) {
1091 while (*v) {
1092 count1++;
1093 v++;
1094 }
1095 }
1096 count2 = 0;
1097 v = add;
1098 while (*v) {
1099 count2++;
1100 v++;
1101 }
1102 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1103 v[count1 + count2] = NULL;
1104 i = count2;
1105 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001106 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001107 return v;
1108}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001109#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001110static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1111{
1112 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1113 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1114 return ptr;
1115}
1116#define add_strings_to_strings(strings, add, need_to_dup) \
1117 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1118#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001119
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001120/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001121static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001122{
1123 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001124 v[0] = add;
1125 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001126 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001127}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001128#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001129static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1130{
1131 char **ptr = add_string_to_strings(strings, add);
1132 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1133 return ptr;
1134}
1135#define add_string_to_strings(strings, add) \
1136 xx_add_string_to_strings(__LINE__, strings, add)
1137#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001138
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001139static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001140{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001141 char **v;
1142
1143 if (!strings)
1144 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001145 v = strings;
1146 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001147 free(*v);
1148 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001149 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001150 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001151}
1152
Denis Vlasenko76d50412008-06-10 16:19:39 +00001153
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001154/* Helpers for setting new $n and restoring them back
1155 */
1156typedef struct save_arg_t {
1157 char *sv_argv0;
1158 char **sv_g_argv;
1159 int sv_g_argc;
1160 smallint sv_g_malloced;
1161} save_arg_t;
1162
1163static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1164{
1165 int n;
1166
1167 sv->sv_argv0 = argv[0];
1168 sv->sv_g_argv = G.global_argv;
1169 sv->sv_g_argc = G.global_argc;
1170 sv->sv_g_malloced = G.global_args_malloced;
1171
1172 argv[0] = G.global_argv[0]; /* retain $0 */
1173 G.global_argv = argv;
1174 G.global_args_malloced = 0;
1175
1176 n = 1;
1177 while (*++argv)
1178 n++;
1179 G.global_argc = n;
1180}
1181
1182static void restore_G_args(save_arg_t *sv, char **argv)
1183{
1184 char **pp;
1185
1186 if (G.global_args_malloced) {
1187 /* someone ran "set -- arg1 arg2 ...", undo */
1188 pp = G.global_argv;
1189 while (*++pp) /* note: does not free $0 */
1190 free(*pp);
1191 free(G.global_argv);
1192 }
1193 argv[0] = sv->sv_argv0;
1194 G.global_argv = sv->sv_g_argv;
1195 G.global_argc = sv->sv_g_argc;
1196 G.global_args_malloced = sv->sv_g_malloced;
1197}
1198
1199
Denis Vlasenkod5762932009-03-31 11:22:57 +00001200/* Basic theory of signal handling in shell
1201 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001202 * This does not describe what hush does, rather, it is current understanding
1203 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001204 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1205 *
1206 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1207 * is finished or backgrounded. It is the same in interactive and
1208 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001209 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001210 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001211 * backgrounds (i.e. stops) or kills all members of currently running
1212 * pipe.
1213 *
1214 * Wait builtin in interruptible by signals for which user trap is set
1215 * or by SIGINT in interactive shell.
1216 *
1217 * Trap handlers will execute even within trap handlers. (right?)
1218 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001219 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1220 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001221 *
1222 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001223 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001224 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001225 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001226 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001227 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001228 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001229 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001230 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001231 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001232 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001233 *
1234 * SIGQUIT: ignore
1235 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001236 * SIGHUP (interactive):
1237 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001238 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001239 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1240 * that all pipe members are stopped. Try this in bash:
1241 * while :; do :; done - ^Z does not background it
1242 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001243 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001244 * of the command line, show prompt. NB: ^C does not send SIGINT
1245 * to interactive shell while shell is waiting for a pipe,
1246 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001247 * Example 1: this waits 5 sec, but does not execute ls:
1248 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1249 * Example 2: this does not wait and does not execute ls:
1250 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1251 * Example 3: this does not wait 5 sec, but executes ls:
1252 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001253 *
1254 * (What happens to signals which are IGN on shell start?)
1255 * (What happens with signal mask on shell start?)
1256 *
1257 * Implementation in hush
1258 * ======================
1259 * We use in-kernel pending signal mask to determine which signals were sent.
1260 * We block all signals which we don't want to take action immediately,
1261 * i.e. we block all signals which need to have special handling as described
1262 * above, and all signals which have traps set.
1263 * After each pipe execution, we extract any pending signals via sigtimedwait()
1264 * and act on them.
1265 *
1266 * unsigned non_DFL_mask: a mask of such "special" signals
1267 * sigset_t blocked_set: current blocked signal set
1268 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001269 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001270 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001271 * "trap 'cmd' SIGxxx":
1272 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001273 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001274 * unblock signals with special interactive handling
1275 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001276 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001277 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001278 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001279 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001280 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001281 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001282 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001283 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001284 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001285 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001286 * Standard says "When a subshell is entered, traps that are not being ignored
1287 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001288 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001289 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001290enum {
1291 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001292 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001293 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001294 | (1 << SIGHUP)
1295 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001296 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001297#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001298 | (1 << SIGTTIN)
1299 | (1 << SIGTTOU)
1300 | (1 << SIGTSTP)
1301#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001302};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001303
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001304#if ENABLE_HUSH_FAST
1305static void SIGCHLD_handler(int sig UNUSED_PARAM)
1306{
1307 G.count_SIGCHLD++;
1308//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1309}
1310#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001311
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001312#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001313
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001314/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001315# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001316/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001317# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001318
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001319/* Restores tty foreground process group, and exits.
1320 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001321 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001322 * or called directly with -EXITCODE.
1323 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001324static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001325static void sigexit(int sig)
1326{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001327 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001328 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001329
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001330 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001331 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001332 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1333 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001334
1335 /* Not a signal, just exit */
1336 if (sig <= 0)
1337 _exit(- sig);
1338
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001339 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001340}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001341#else
1342
Denys Vlasenko8391c482010-05-22 17:50:43 +02001343# define disable_restore_tty_pgrp_on_exit() ((void)0)
1344# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001345
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001346#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001347
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001348/* Restores tty foreground process group, and exits. */
1349static void hush_exit(int exitcode) NORETURN;
1350static void hush_exit(int exitcode)
1351{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001352 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1353 /* Prevent recursion:
1354 * trap "echo Hi; exit" EXIT; exit
1355 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001356 char *argv[3];
1357 /* argv[0] is unused */
1358 argv[1] = G.traps[0];
1359 argv[2] = NULL;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001360 G.traps[0] = NULL;
1361 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001362 builtin_eval(argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001363 /* free(argv[1]); - why bother */
Denis Vlasenkod5762932009-03-31 11:22:57 +00001364 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001365
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001366#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001367 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001368 sigexit(- (exitcode & 0xff));
1369#else
1370 exit(exitcode);
1371#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001372}
1373
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001374
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001375static int check_and_run_traps(int sig)
1376{
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001377 /* I want it in rodata, not in bss.
1378 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1379 * initializer. But other compilers may still use bss.
1380 * TODO: find more portable solution.
1381 */
1382 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001383 smalluint save_rcode;
1384 int last_sig = 0;
1385
1386 if (sig)
1387 goto jump_in;
1388 while (1) {
1389 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1390 if (sig <= 0)
1391 break;
1392 jump_in:
1393 last_sig = sig;
1394 if (G.traps && G.traps[sig]) {
1395 if (G.traps[sig][0]) {
1396 /* We have user-defined handler */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001397 char *argv[3];
1398 /* argv[0] is unused */
1399 argv[1] = G.traps[sig];
1400 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001401 save_rcode = G.last_exitcode;
1402 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001403 G.last_exitcode = save_rcode;
1404 } /* else: "" trap, ignoring signal */
1405 continue;
1406 }
1407 /* not a trap: special action */
1408 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001409#if ENABLE_HUSH_FAST
1410 case SIGCHLD:
1411 G.count_SIGCHLD++;
1412//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1413 break;
1414#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001415 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001416 /* Builtin was ^C'ed, make it look prettier: */
1417 bb_putchar('\n');
1418 G.flag_SIGINT = 1;
1419 break;
1420#if ENABLE_HUSH_JOB
1421 case SIGHUP: {
1422 struct pipe *job;
1423 /* bash is observed to signal whole process groups,
1424 * not individual processes */
1425 for (job = G.job_list; job; job = job->next) {
1426 if (job->pgrp <= 0)
1427 continue;
1428 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1429 if (kill(- job->pgrp, SIGHUP) == 0)
1430 kill(- job->pgrp, SIGCONT);
1431 }
1432 sigexit(SIGHUP);
1433 }
1434#endif
1435 default: /* ignored: */
1436 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1437 break;
1438 }
1439 }
1440 return last_sig;
1441}
1442
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001443
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001444static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001445{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001446 if (force || G.cwd == NULL) {
1447 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1448 * we must not try to free(bb_msg_unknown) */
1449 if (G.cwd == bb_msg_unknown)
1450 G.cwd = NULL;
1451 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1452 if (!G.cwd)
1453 G.cwd = bb_msg_unknown;
1454 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001455 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001456}
1457
Denis Vlasenko83506862007-11-23 13:11:42 +00001458
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001459/*
1460 * Shell and environment variable support
1461 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001462static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001463{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001464 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001465 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001466
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001467 pp = &G.top_var;
1468 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001469 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001470 return pp;
1471 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001472 }
1473 return NULL;
1474}
1475
Denys Vlasenko03dad222010-01-12 23:29:57 +01001476static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001477{
Denys Vlasenko29082232010-07-16 13:52:32 +02001478 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001479 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001480
1481 if (G.expanded_assignments) {
1482 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001483 while (*cpp) {
1484 char *cp = *cpp;
1485 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1486 return cp + len + 1;
1487 cpp++;
1488 }
1489 }
1490
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001491 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001492 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001493 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001494
Denys Vlasenkodea47882009-10-09 15:40:49 +02001495 if (strcmp(name, "PPID") == 0)
1496 return utoa(G.root_ppid);
1497 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001498#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001499 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001500 return utoa(next_random(&G.random_gen));
1501#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001502 return NULL;
1503}
1504
1505/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001506 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001507 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001508 * 0: do not change export flag
1509 * (if creating new variable, flag will be 0)
1510 * 1: set export flag and putenv the variable
1511 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001512 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001513 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001514#if !BB_MMU && ENABLE_HUSH_LOCAL
1515/* all params are used */
1516#elif BB_MMU && ENABLE_HUSH_LOCAL
1517#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1518 set_local_var(str, flg_export, local_lvl)
1519#elif BB_MMU && !ENABLE_HUSH_LOCAL
1520#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001521 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001522#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1523#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1524 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001525#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001526static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001527{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001528 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001529 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001530 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001531 int name_len;
1532
Denis Vlasenko950bd722009-04-21 11:23:56 +00001533 eq_sign = strchr(str, '=');
1534 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001535 free(str);
1536 return -1;
1537 }
1538
Denis Vlasenko950bd722009-04-21 11:23:56 +00001539 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001540 var_pp = &G.top_var;
1541 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001542 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001543 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001544 continue;
1545 }
1546 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001547 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001548#if !BB_MMU
1549 if (!flg_read_only)
1550#endif
1551 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001552 free(str);
1553 return -1;
1554 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001555 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001556 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1557 *eq_sign = '\0';
1558 unsetenv(str);
1559 *eq_sign = '=';
1560 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001561#if ENABLE_HUSH_LOCAL
1562 if (cur->func_nest_level < local_lvl) {
1563 /* New variable is declared as local,
1564 * and existing one is global, or local
1565 * from enclosing function.
1566 * Remove and save old one: */
1567 *var_pp = cur->next;
1568 cur->next = *G.shadowed_vars_pp;
1569 *G.shadowed_vars_pp = cur;
1570 /* bash 3.2.33(1) and exported vars:
1571 * # export z=z
1572 * # f() { local z=a; env | grep ^z; }
1573 * # f
1574 * z=a
1575 * # env | grep ^z
1576 * z=z
1577 */
1578 if (cur->flg_export)
1579 flg_export = 1;
1580 break;
1581 }
1582#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001583 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001584 free_and_exp:
1585 free(str);
1586 goto exp;
1587 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001588 if (cur->max_len != 0) {
1589 if (cur->max_len >= strlen(str)) {
1590 /* This one is from startup env, reuse space */
1591 strcpy(cur->varstr, str);
1592 goto free_and_exp;
1593 }
1594 } else {
1595 /* max_len == 0 signifies "malloced" var, which we can
1596 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001597 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001598 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001599 cur->max_len = 0;
1600 goto set_str_and_exp;
1601 }
1602
Denys Vlasenko295fef82009-06-03 12:47:26 +02001603 /* Not found - create new variable struct */
1604 cur = xzalloc(sizeof(*cur));
1605#if ENABLE_HUSH_LOCAL
1606 cur->func_nest_level = local_lvl;
1607#endif
1608 cur->next = *var_pp;
1609 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001610
1611 set_str_and_exp:
1612 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001613#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001614 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001615#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001616 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001617 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001618 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001619 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1620 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001621 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001622 if (flg_export == -1) {
1623 cur->flg_export = 0;
1624 /* unsetenv was already done */
1625 } else {
1626 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1627 return putenv(cur->varstr);
1628 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001629 }
1630 return 0;
1631}
1632
Denys Vlasenko6db47842009-09-05 20:15:17 +02001633/* Used at startup and after each cd */
1634static void set_pwd_var(int exp)
1635{
1636 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1637 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1638}
1639
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001640static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001641{
1642 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001643 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001644
1645 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001646 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001647 var_pp = &G.top_var;
1648 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001649 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1650 if (cur->flg_read_only) {
1651 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001652 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001653 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001654 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001655 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1656 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001657 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1658 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001659 if (!cur->max_len)
1660 free(cur->varstr);
1661 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001662 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001663 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001664 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001665 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001666 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001667}
1668
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001669static int unset_local_var(const char *name)
1670{
1671 return unset_local_var_len(name, strlen(name));
1672}
1673
1674static void unset_vars(char **strings)
1675{
1676 char **v;
1677
1678 if (!strings)
1679 return;
1680 v = strings;
1681 while (*v) {
1682 const char *eq = strchrnul(*v, '=');
1683 unset_local_var_len(*v, (int)(eq - *v));
1684 v++;
1685 }
1686 free(strings);
1687}
1688
Denys Vlasenko03dad222010-01-12 23:29:57 +01001689static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001690{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001691 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001692 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001693}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001694
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001695
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001696/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001697 * Helpers for "var1=val1 var2=val2 cmd" feature
1698 */
1699static void add_vars(struct variable *var)
1700{
1701 struct variable *next;
1702
1703 while (var) {
1704 next = var->next;
1705 var->next = G.top_var;
1706 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001707 if (var->flg_export) {
1708 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001709 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001710 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001711 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001712 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001713 var = next;
1714 }
1715}
1716
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001717static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001718{
1719 char **s;
1720 struct variable *old = NULL;
1721
1722 if (!strings)
1723 return old;
1724 s = strings;
1725 while (*s) {
1726 struct variable *var_p;
1727 struct variable **var_pp;
1728 char *eq;
1729
1730 eq = strchr(*s, '=');
1731 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001732 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001733 if (var_pp) {
1734 /* Remove variable from global linked list */
1735 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001736 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001737 *var_pp = var_p->next;
1738 /* Add it to returned list */
1739 var_p->next = old;
1740 old = var_p;
1741 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001742 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001743 }
1744 s++;
1745 }
1746 return old;
1747}
1748
1749
1750/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001751 * in_str support
1752 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001753static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001754{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001755 int ch = *i->p;
1756 if (ch != '\0') {
1757 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001758 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001759 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001760 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001761}
1762
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001763static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001764{
1765 return *i->p;
1766}
1767
1768#if ENABLE_HUSH_INTERACTIVE
1769
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001770static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001771{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001772 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001773 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001774 if (G.PS1 == NULL)
1775 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001776 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001777 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001778 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001779 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001780 if (G.PS2 == NULL)
1781 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001782}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001783
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001784static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001785{
1786 const char *prompt_str;
1787 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001788 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1789 /* Set up the prompt */
1790 if (promptmode == 0) { /* PS1 */
1791 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001792 /* bash uses $PWD value, even if it is set by user.
1793 * It uses current dir only if PWD is unset.
1794 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001795 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001796 prompt_str = G.PS1;
1797 } else
1798 prompt_str = G.PS2;
1799 } else
1800 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001801 debug_printf("result '%s'\n", prompt_str);
1802 return prompt_str;
1803}
1804
1805static void get_user_input(struct in_str *i)
1806{
1807 int r;
1808 const char *prompt_str;
1809
1810 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001811# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001812 /* Enable command line editing only while a command line
1813 * is actually being read */
1814 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001815 G.flag_SIGINT = 0;
1816 /* buglet: SIGINT will not make new prompt to appear _at once_,
1817 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001818 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 +00001819 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001820 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001821 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001822 i->eof_flag = (r < 0);
1823 if (i->eof_flag) { /* EOF/error detected */
1824 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1825 G.user_input_buf[1] = '\0';
1826 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001827# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001828 do {
1829 G.flag_SIGINT = 0;
1830 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001831 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001832 G.user_input_buf[0] = r = fgetc(i->file);
1833 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001834//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001835 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001836 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001837# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001838 i->p = G.user_input_buf;
1839}
1840
1841#endif /* INTERACTIVE */
1842
1843/* This is the magic location that prints prompts
1844 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001845static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001846{
1847 int ch;
1848
1849 /* If there is data waiting, eat it up */
1850 if (i->p && *i->p) {
1851#if ENABLE_HUSH_INTERACTIVE
1852 take_cached:
1853#endif
1854 ch = *i->p++;
1855 if (i->eof_flag && !*i->p)
1856 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001857 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001858 } else {
1859 /* need to double check i->file because we might be doing something
1860 * more complicated by now, like sourcing or substituting. */
1861#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001862 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001863 do {
1864 get_user_input(i);
1865 } while (!*i->p); /* need non-empty line */
1866 i->promptmode = 1; /* PS2 */
1867 i->promptme = 0;
1868 goto take_cached;
1869 }
1870#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001871 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001872 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001873 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001874#if ENABLE_HUSH_INTERACTIVE
1875 if (ch == '\n')
1876 i->promptme = 1;
1877#endif
1878 return ch;
1879}
1880
Denis Vlasenko913a2012009-04-05 22:17:04 +00001881/* All callers guarantee this routine will never
1882 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001883 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001884static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001885{
1886 int ch;
1887 if (i->p && *i->p) {
1888 if (i->eof_flag && !i->p[1])
1889 return EOF;
1890 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001891 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001892 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001893 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001894 i->eof_flag = (ch == EOF);
1895 i->peek_buf[0] = ch;
1896 i->peek_buf[1] = '\0';
1897 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001898 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001899 return ch;
1900}
1901
1902static void setup_file_in_str(struct in_str *i, FILE *f)
1903{
1904 i->peek = file_peek;
1905 i->get = file_get;
1906#if ENABLE_HUSH_INTERACTIVE
1907 i->promptme = 1;
1908 i->promptmode = 0; /* PS1 */
1909#endif
1910 i->file = f;
1911 i->p = NULL;
1912}
1913
1914static void setup_string_in_str(struct in_str *i, const char *s)
1915{
1916 i->peek = static_peek;
1917 i->get = static_get;
1918#if ENABLE_HUSH_INTERACTIVE
1919 i->promptme = 1;
1920 i->promptmode = 0; /* PS1 */
1921#endif
1922 i->p = s;
1923 i->eof_flag = 0;
1924}
1925
1926
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001927/*
1928 * o_string support
1929 */
1930#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001931
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001932static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001933{
1934 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02001935 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001936 if (o->data)
1937 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001938}
1939
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001940static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001941{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001942 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001943 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001944}
1945
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001946static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1947{
1948 free(o->data);
1949}
1950
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001951static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001952{
1953 if (o->length + len > o->maxlen) {
1954 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1955 o->data = xrealloc(o->data, 1 + o->maxlen);
1956 }
1957}
1958
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001959static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001960{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001961 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1962 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001963 o->data[o->length] = ch;
1964 o->length++;
1965 o->data[o->length] = '\0';
1966}
1967
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001968static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001969{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001970 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001971 memcpy(&o->data[o->length], str, len);
1972 o->length += len;
1973 o->data[o->length] = '\0';
1974}
1975
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001976static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001977{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001978 o_addblock(o, str, strlen(str));
1979}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02001980
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001981#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001982static void nommu_addchr(o_string *o, int ch)
1983{
1984 if (o)
1985 o_addchr(o, ch);
1986}
1987#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001988# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001989#endif
1990
1991static void o_addstr_with_NUL(o_string *o, const char *str)
1992{
1993 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001994}
1995
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001996static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001997{
1998 while (len) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001999 len--;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002000 o_addchr(o, *str);
2001 if (*str++ == '\\') {
2002 /* \z -> \\\z; \<eol> -> \\<eol> */
2003 o_addchr(o, '\\');
2004 if (len) {
2005 len--;
2006 o_addchr(o, '\\');
2007 o_addchr(o, *str++);
2008 }
2009 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002010 }
2011}
2012
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002013#undef HUSH_BRACE_EXP
2014/*
2015 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2016 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2017 * Apparently, on unquoted $v bash still does globbing
2018 * ("v='*.txt'; echo $v" prints all .txt files),
2019 * but NOT brace expansion! Thus, there should be TWO independent
2020 * quoting mechanisms on $v expansion side: one protects
2021 * $v from brace expansion, and other additionally protects "$v" against globbing.
2022 * We have only second one.
2023 */
2024
2025#ifdef HUSH_BRACE_EXP
2026# define MAYBE_BRACES "{}"
2027#else
2028# define MAYBE_BRACES ""
2029#endif
2030
Eric Andersen25f27032001-04-26 23:22:31 +00002031/* My analysis of quoting semantics tells me that state information
2032 * is associated with a destination, not a source.
2033 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002034static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002035{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002036 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002037 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002038 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002039 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002040 o_grow_by(o, sz);
2041 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002042 o->data[o->length] = '\\';
2043 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002044 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002045 o->data[o->length] = ch;
2046 o->length++;
2047 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002048}
2049
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002050static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002051{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002052 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002053 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2054 && strchr("*?[\\" MAYBE_BRACES, ch)
2055 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002056 sz++;
2057 o->data[o->length] = '\\';
2058 o->length++;
2059 }
2060 o_grow_by(o, sz);
2061 o->data[o->length] = ch;
2062 o->length++;
2063 o->data[o->length] = '\0';
2064}
2065
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002066static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002067{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002068 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002069 char ch;
2070 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002071 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002072 if (ordinary_cnt > len) /* paranoia */
2073 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002074 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002075 if (ordinary_cnt == len)
2076 return;
2077 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002078 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002079
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002080 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002081 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002082 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002083 sz++;
2084 o->data[o->length] = '\\';
2085 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002086 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002087 o_grow_by(o, sz);
2088 o->data[o->length] = ch;
2089 o->length++;
2090 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002091 }
2092}
2093
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002094static void o_addQblock(o_string *o, const char *str, int len)
2095{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002096 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002097 o_addblock(o, str, len);
2098 return;
2099 }
2100 o_addqblock(o, str, len);
2101}
2102
Denys Vlasenko38292b62010-09-05 14:49:40 +02002103static void o_addQstr(o_string *o, const char *str)
2104{
2105 o_addQblock(o, str, strlen(str));
2106}
2107
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002108/* A special kind of o_string for $VAR and `cmd` expansion.
2109 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002110 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002111 * list[i] contains an INDEX (int!) into this string data.
2112 * It means that if list[] needs to grow, data needs to be moved higher up
2113 * but list[i]'s need not be modified.
2114 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002115 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002116 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2117 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002118#if DEBUG_EXPAND || DEBUG_GLOB
2119static void debug_print_list(const char *prefix, o_string *o, int n)
2120{
2121 char **list = (char**)o->data;
2122 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2123 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002124
2125 indent();
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002126 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 +02002127 prefix, list, n, string_start, o->length, o->maxlen,
2128 !!(o->o_expflags & EXP_FLAG_GLOB),
2129 o->has_quoted_part,
2130 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002131 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002132 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002133 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2134 o->data + (int)list[i] + string_start,
2135 o->data + (int)list[i] + string_start);
2136 i++;
2137 }
2138 if (n) {
2139 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002140 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002141 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002142 }
2143}
2144#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002145# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002146#endif
2147
2148/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2149 * in list[n] so that it points past last stored byte so far.
2150 * It returns n+1. */
2151static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002152{
2153 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002154 int string_start;
2155 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002156
2157 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002158 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2159 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002160 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002161 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002162 /* list[n] points to string_start, make space for 16 more pointers */
2163 o->maxlen += 0x10 * sizeof(list[0]);
2164 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002165 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002166 memmove(list + n + 0x10, list + n, string_len);
2167 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002168 } else {
2169 debug_printf_list("list[%d]=%d string_start=%d\n",
2170 n, string_len, string_start);
2171 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002172 } else {
2173 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002174 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2175 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002176 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2177 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002178 o->has_empty_slot = 0;
2179 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002180 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002181 return n + 1;
2182}
2183
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002184/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002185static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002186{
2187 char **list = (char**)o->data;
2188 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2189
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002190 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002191}
2192
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002193#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002194/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2195 * first, it processes even {a} (no commas), second,
2196 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002197 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002198 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002199
2200/* Helper */
2201static int glob_needed(const char *s)
2202{
2203 while (*s) {
2204 if (*s == '\\') {
2205 if (!s[1])
2206 return 0;
2207 s += 2;
2208 continue;
2209 }
2210 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2211 return 1;
2212 s++;
2213 }
2214 return 0;
2215}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002216/* Return pointer to next closing brace or to comma */
2217static const char *next_brace_sub(const char *cp)
2218{
2219 unsigned depth = 0;
2220 cp++;
2221 while (*cp != '\0') {
2222 if (*cp == '\\') {
2223 if (*++cp == '\0')
2224 break;
2225 cp++;
2226 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002227 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002228 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002229 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002230 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002231 depth++;
2232 }
2233
2234 return *cp != '\0' ? cp : NULL;
2235}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002236/* Recursive brace globber. Note: may garble pattern[]. */
2237static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002238{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002239 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002240 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002241 const char *next;
2242 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002243 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002244 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002245
2246 debug_printf_glob("glob_brace('%s')\n", pattern);
2247
2248 begin = pattern;
2249 while (1) {
2250 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002251 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002252 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002253 /* Find the first sub-pattern and at the same time
2254 * find the rest after the closing brace */
2255 next = next_brace_sub(begin);
2256 if (next == NULL) {
2257 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002258 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002259 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002260 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002261 /* "{abc}" with no commas - illegal
2262 * brace expr, disregard and skip it */
2263 begin = next + 1;
2264 continue;
2265 }
2266 break;
2267 }
2268 if (*begin == '\\' && begin[1] != '\0')
2269 begin++;
2270 begin++;
2271 }
2272 debug_printf_glob("begin:%s\n", begin);
2273 debug_printf_glob("next:%s\n", next);
2274
2275 /* Now find the end of the whole brace expression */
2276 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002277 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002278 rest = next_brace_sub(rest);
2279 if (rest == NULL) {
2280 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002281 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002282 }
2283 debug_printf_glob("rest:%s\n", rest);
2284 }
2285 rest_len = strlen(++rest) + 1;
2286
2287 /* We are sure the brace expression is well-formed */
2288
2289 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002290 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002291
2292 /* We have a brace expression. BEGIN points to the opening {,
2293 * NEXT points past the terminator of the first element, and REST
2294 * points past the final }. We will accumulate result names from
2295 * recursive runs for each brace alternative in the buffer using
2296 * GLOB_APPEND. */
2297
2298 p = begin + 1;
2299 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002300 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002301 memcpy(
2302 mempcpy(
2303 mempcpy(new_pattern_buf,
2304 /* We know the prefix for all sub-patterns */
2305 pattern, begin - pattern),
2306 p, next - p),
2307 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002308
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002309 /* Note: glob_brace() may garble new_pattern_buf[].
2310 * That's why we re-copy prefix every time (1st memcpy above).
2311 */
2312 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002313 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002314 /* We saw the last entry */
2315 break;
2316 }
2317 p = next + 1;
2318 next = next_brace_sub(next);
2319 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002320 free(new_pattern_buf);
2321 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002322
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002323 simple_glob:
2324 {
2325 int gr;
2326 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002327
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002328 memset(&globdata, 0, sizeof(globdata));
2329 gr = glob(pattern, 0, NULL, &globdata);
2330 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2331 if (gr != 0) {
2332 if (gr == GLOB_NOMATCH) {
2333 globfree(&globdata);
2334 /* NB: garbles parameter */
2335 unbackslash(pattern);
2336 o_addstr_with_NUL(o, pattern);
2337 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2338 return o_save_ptr_helper(o, n);
2339 }
2340 if (gr == GLOB_NOSPACE)
2341 bb_error_msg_and_die(bb_msg_memory_exhausted);
2342 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2343 * but we didn't specify it. Paranoia again. */
2344 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2345 }
2346 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2347 char **argv = globdata.gl_pathv;
2348 while (1) {
2349 o_addstr_with_NUL(o, *argv);
2350 n = o_save_ptr_helper(o, n);
2351 argv++;
2352 if (!*argv)
2353 break;
2354 }
2355 }
2356 globfree(&globdata);
2357 }
2358 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002359}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002360/* Performs globbing on last list[],
2361 * saving each result as a new list[].
2362 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002363static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002364{
2365 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002366
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002367 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002368 if (!o->data)
2369 return o_save_ptr_helper(o, n);
2370 pattern = o->data + o_get_last_ptr(o, n);
2371 debug_printf_glob("glob pattern '%s'\n", pattern);
2372 if (!glob_needed(pattern)) {
2373 /* unbackslash last string in o in place, fix length */
2374 o->length = unbackslash(pattern) - o->data;
2375 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2376 return o_save_ptr_helper(o, n);
2377 }
2378
2379 copy = xstrdup(pattern);
2380 /* "forget" pattern in o */
2381 o->length = pattern - o->data;
2382 n = glob_brace(copy, o, n);
2383 free(copy);
2384 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002385 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002386 return n;
2387}
2388
Denys Vlasenko8391c482010-05-22 17:50:43 +02002389#else /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002390
2391/* Helper */
2392static int glob_needed(const char *s)
2393{
2394 while (*s) {
2395 if (*s == '\\') {
2396 if (!s[1])
2397 return 0;
2398 s += 2;
2399 continue;
2400 }
2401 if (*s == '*' || *s == '[' || *s == '?')
2402 return 1;
2403 s++;
2404 }
2405 return 0;
2406}
2407/* Performs globbing on last list[],
2408 * saving each result as a new list[].
2409 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002410static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002411{
2412 glob_t globdata;
2413 int gr;
2414 char *pattern;
2415
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002416 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002417 if (!o->data)
2418 return o_save_ptr_helper(o, n);
2419 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002420 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002421 if (!glob_needed(pattern)) {
2422 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002423 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002424 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002425 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002426 return o_save_ptr_helper(o, n);
2427 }
2428
2429 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002430 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2431 * If we glob "*.\*" and don't find anything, we need
2432 * to fall back to using literal "*.*", but GLOB_NOCHECK
2433 * will return "*.\*"!
2434 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002435 gr = glob(pattern, 0, NULL, &globdata);
2436 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002437 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002438 if (gr == GLOB_NOMATCH) {
2439 globfree(&globdata);
2440 goto literal;
2441 }
2442 if (gr == GLOB_NOSPACE)
2443 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002444 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2445 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002446 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002447 }
2448 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2449 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002450 /* "forget" pattern in o */
2451 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002452 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002453 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002454 n = o_save_ptr_helper(o, n);
2455 argv++;
2456 if (!*argv)
2457 break;
2458 }
2459 }
2460 globfree(&globdata);
2461 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002462 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002463 return n;
2464}
2465
Denys Vlasenko8391c482010-05-22 17:50:43 +02002466#endif /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002467
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002468/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002469 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002470static int o_save_ptr(o_string *o, int n)
2471{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002472 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002473 /* If o->has_empty_slot, list[n] was already globbed
2474 * (if it was requested back then when it was filled)
2475 * so don't do that again! */
2476 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002477 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002478 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002479 return o_save_ptr_helper(o, n);
2480}
2481
2482/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002483static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002484{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002485 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002486 int string_start;
2487
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002488 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2489 if (DEBUG_EXPAND)
2490 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002491 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002492 list = (char**)o->data;
2493 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2494 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002495 while (n) {
2496 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002497 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002498 }
2499 return list;
2500}
2501
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002502static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002503
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002504/* Returns pi->next - next pipe in the list */
2505static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002506{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002507 struct pipe *next;
2508 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002509
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002510 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002511 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002512 struct command *command;
2513 struct redir_struct *r, *rnext;
2514
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002515 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002516 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002517 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002518 if (DEBUG_CLEAN) {
2519 int a;
2520 char **p;
2521 for (a = 0, p = command->argv; *p; a++, p++) {
2522 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2523 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002524 }
2525 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002526 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002527 }
2528 /* not "else if": on syntax error, we may have both! */
2529 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002530 debug_printf_clean(" begin group (cmd_type:%d)\n",
2531 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002532 free_pipe_list(command->group);
2533 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002534 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002535 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002536 /* else is crucial here.
2537 * If group != NULL, child_func is meaningless */
2538#if ENABLE_HUSH_FUNCTIONS
2539 else if (command->child_func) {
2540 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2541 command->child_func->parent_cmd = NULL;
2542 }
2543#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002544#if !BB_MMU
2545 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002546 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002547#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002548 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002549 debug_printf_clean(" redirect %d%s",
2550 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002551 /* guard against the case >$FOO, where foo is unset or blank */
2552 if (r->rd_filename) {
2553 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2554 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002555 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002557 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002558 rnext = r->next;
2559 free(r);
2560 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002561 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002562 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002563 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002564 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002565#if ENABLE_HUSH_JOB
2566 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002567 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002568#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002569
2570 next = pi->next;
2571 free(pi);
2572 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002573}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002574
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002575static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002576{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002577 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002578#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002579 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002580#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002581 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002582 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002583 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002584}
2585
2586
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002587/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002588
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002589static struct pipe *new_pipe(void)
2590{
Eric Andersen25f27032001-04-26 23:22:31 +00002591 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002592 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002593 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002594 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002595 return pi;
2596}
2597
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002598/* Command (member of a pipe) is complete, or we start a new pipe
2599 * if ctx->command is NULL.
2600 * No errors possible here.
2601 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002602static int done_command(struct parse_context *ctx)
2603{
2604 /* The command is really already in the pipe structure, so
2605 * advance the pipe counter and make a new, null command. */
2606 struct pipe *pi = ctx->pipe;
2607 struct command *command = ctx->command;
2608
2609 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002610 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002611 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002612 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002613 }
2614 pi->num_cmds++;
2615 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002616 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002617 } else {
2618 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2619 }
2620
2621 /* Only real trickiness here is that the uncommitted
2622 * command structure is not counted in pi->num_cmds. */
2623 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002624 ctx->command = command = &pi->cmds[pi->num_cmds];
2625 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002626 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002627 return pi->num_cmds; /* used only for 0/nonzero check */
2628}
2629
2630static void done_pipe(struct parse_context *ctx, pipe_style type)
2631{
2632 int not_null;
2633
2634 debug_printf_parse("done_pipe entered, followup %d\n", type);
2635 /* Close previous command */
2636 not_null = done_command(ctx);
2637 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002638#if HAS_KEYWORDS
2639 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2640 ctx->ctx_inverted = 0;
2641 ctx->pipe->res_word = ctx->ctx_res_w;
2642#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002643
2644 /* Without this check, even just <enter> on command line generates
2645 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002646 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002647 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002648#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002649 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002650#endif
2651#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002652 || ctx->ctx_res_w == RES_DONE
2653 || ctx->ctx_res_w == RES_FOR
2654 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002655#endif
2656#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002657 || ctx->ctx_res_w == RES_ESAC
2658#endif
2659 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002660 struct pipe *new_p;
2661 debug_printf_parse("done_pipe: adding new pipe: "
2662 "not_null:%d ctx->ctx_res_w:%d\n",
2663 not_null, ctx->ctx_res_w);
2664 new_p = new_pipe();
2665 ctx->pipe->next = new_p;
2666 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002667 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002668 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002669 * This is used to control execution.
2670 * RES_FOR and RES_IN are NOT sticky (needed to support
2671 * cases where variable or value happens to match a keyword):
2672 */
2673#if ENABLE_HUSH_LOOPS
2674 if (ctx->ctx_res_w == RES_FOR
2675 || ctx->ctx_res_w == RES_IN)
2676 ctx->ctx_res_w = RES_NONE;
2677#endif
2678#if ENABLE_HUSH_CASE
2679 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002680 ctx->ctx_res_w = RES_CASE_BODY;
2681 if (ctx->ctx_res_w == RES_CASE)
2682 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002683#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002684 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002685 /* Create the memory for command, roughly:
2686 * ctx->pipe->cmds = new struct command;
2687 * ctx->command = &ctx->pipe->cmds[0];
2688 */
2689 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002690 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002691 }
2692 debug_printf_parse("done_pipe return\n");
2693}
2694
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002695static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002696{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002697 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002698 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002699 /* Create the memory for command, roughly:
2700 * ctx->pipe->cmds = new struct command;
2701 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002702 */
2703 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002704}
2705
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002706/* If a reserved word is found and processed, parse context is modified
2707 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002708 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002709#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002710struct reserved_combo {
2711 char literal[6];
2712 unsigned char res;
2713 unsigned char assignment_flag;
2714 int flag;
2715};
2716enum {
2717 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002718# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002719 FLAG_IF = (1 << RES_IF ),
2720 FLAG_THEN = (1 << RES_THEN ),
2721 FLAG_ELIF = (1 << RES_ELIF ),
2722 FLAG_ELSE = (1 << RES_ELSE ),
2723 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002724# endif
2725# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002726 FLAG_FOR = (1 << RES_FOR ),
2727 FLAG_WHILE = (1 << RES_WHILE),
2728 FLAG_UNTIL = (1 << RES_UNTIL),
2729 FLAG_DO = (1 << RES_DO ),
2730 FLAG_DONE = (1 << RES_DONE ),
2731 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002732# endif
2733# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002734 FLAG_MATCH = (1 << RES_MATCH),
2735 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002736# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002737 FLAG_START = (1 << RES_XXXX ),
2738};
2739
2740static const struct reserved_combo* match_reserved_word(o_string *word)
2741{
Eric Andersen25f27032001-04-26 23:22:31 +00002742 /* Mostly a list of accepted follow-up reserved words.
2743 * FLAG_END means we are done with the sequence, and are ready
2744 * to turn the compound list into a command.
2745 * FLAG_START means the word must start a new compound list.
2746 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002747 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002748# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002749 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2750 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2751 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2752 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2753 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2754 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002755# endif
2756# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002757 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2758 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2759 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2760 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2761 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2762 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002763# endif
2764# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002765 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2766 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002767# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002768 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002769 const struct reserved_combo *r;
2770
2771 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2772 if (strcmp(word->data, r->literal) == 0)
2773 return r;
2774 }
2775 return NULL;
2776}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002777/* Return 0: not a keyword, 1: keyword
2778 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002779static int reserved_word(o_string *word, struct parse_context *ctx)
2780{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002781# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002782 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002783 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002784 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002785# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002786 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002787
Denys Vlasenko38292b62010-09-05 14:49:40 +02002788 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002789 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002790 r = match_reserved_word(word);
2791 if (!r)
2792 return 0;
2793
2794 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002795# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002796 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2797 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002798 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002799 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002800# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002801 if (r->flag == 0) { /* '!' */
2802 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002803 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002804 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002805 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002806 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002807 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002808 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002809 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002810 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002811
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002812 old = xmalloc(sizeof(*old));
2813 debug_printf_parse("push stack %p\n", old);
2814 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002815 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002816 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002817 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002818 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002819 ctx->ctx_res_w = RES_SNTX;
2820 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002821 } else {
2822 /* "{...} fi" is ok. "{...} if" is not
2823 * Example:
2824 * if { echo foo; } then { echo bar; } fi */
2825 if (ctx->command->group)
2826 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002827 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002828
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002829 ctx->ctx_res_w = r->res;
2830 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002831 word->o_assignment = r->assignment_flag;
2832
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002833 if (ctx->old_flag & FLAG_END) {
2834 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002835
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002836 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002837 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002838 old = ctx->stack;
2839 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002840 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002841# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002842 o_addstr(&old->as_string, ctx->as_string.data);
2843 o_free_unsafe(&ctx->as_string);
2844 old->command->group_as_string = xstrdup(old->as_string.data);
2845 debug_printf_parse("pop, remembering as:'%s'\n",
2846 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002847# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002848 *ctx = *old; /* physical copy */
2849 free(old);
2850 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002851 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002852}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002853#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00002854
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002855/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002856 * Normal return is 0. Syntax errors return 1.
2857 * Note: on return, word is reset, but not o_free'd!
2858 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002859static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002860{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002861 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00002862
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002863 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02002864 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002865 debug_printf_parse("done_word return 0: true null, ignored\n");
2866 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002867 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002868
Eric Andersen25f27032001-04-26 23:22:31 +00002869 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002870 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2871 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002872 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2873 * "2.7 Redirection
2874 * ...the word that follows the redirection operator
2875 * shall be subjected to tilde expansion, parameter expansion,
2876 * command substitution, arithmetic expansion, and quote
2877 * removal. Pathname expansion shall not be performed
2878 * on the word by a non-interactive shell; an interactive
2879 * shell may perform it, but shall do so only when
2880 * the expansion would result in one word."
2881 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002882 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002883 /* Cater for >\file case:
2884 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2885 * Same with heredocs:
2886 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2887 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002888 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2889 unbackslash(ctx->pending_redirect->rd_filename);
2890 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02002891 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002892 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2893 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002894 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002895 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002896 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002897 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002898 /* If this word wasn't an assignment, next ones definitely
2899 * can't be assignments. Even if they look like ones. */
2900 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2901 && word->o_assignment != WORD_IS_KEYWORD
2902 ) {
2903 word->o_assignment = NOT_ASSIGNMENT;
2904 } else {
2905 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2906 command->assignment_cnt++;
2907 word->o_assignment = MAYBE_ASSIGNMENT;
2908 }
2909
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002910#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002911# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00002912 if (ctx->ctx_dsemicolon
2913 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2914 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00002915 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002916 /* ctx->ctx_res_w = RES_MATCH; */
2917 ctx->ctx_dsemicolon = 0;
2918 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002919# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002920 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002921# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002922 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2923 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002924# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002925# if ENABLE_HUSH_CASE
2926 && ctx->ctx_res_w != RES_CASE
2927# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002928 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002929 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002930 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002931 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002932 debug_printf_parse("done_word return %d\n",
2933 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002934 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002935 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002936# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002937 if (strcmp(word->data, "[[") == 0) {
2938 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2939 }
2940 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002941# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002942 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002943#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00002944 if (command->group) {
2945 /* "{ echo foo; } echo bar" - bad */
2946 syntax_error_at(word->data);
2947 debug_printf_parse("done_word return 1: syntax error, "
2948 "groups and arglists don't mix\n");
2949 return 1;
2950 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02002951 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00002952 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2953 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002954 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002955 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002956 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002957 char *p = word->data;
2958 while (p[0] == SPECIAL_VAR_SYMBOL
2959 && (p[1] & 0x7f) == '@'
2960 && p[2] == SPECIAL_VAR_SYMBOL
2961 ) {
2962 p += 3;
2963 }
2964 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002965 /* saw no "$@", or not only "$@" but some
2966 * real text is there too */
2967 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002968 * e.g. "", $empty"" etc to not disappear */
2969 o_addchr(word, SPECIAL_VAR_SYMBOL);
2970 o_addchr(word, SPECIAL_VAR_SYMBOL);
2971 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002972 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002973 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002974 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002975 }
Eric Andersen25f27032001-04-26 23:22:31 +00002976
Denis Vlasenko06810332007-05-21 23:30:54 +00002977#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002978 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02002979 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002980 || !is_well_formed_var_name(command->argv[0], '\0')
2981 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002982 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002983 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002984 return 1;
2985 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002986 /* Force FOR to have just one word (variable name) */
2987 /* NB: basically, this makes hush see "for v in ..."
2988 * syntax as if it is "for v; in ...". FOR and IN become
2989 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002990 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002991 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002992#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002993#if ENABLE_HUSH_CASE
2994 /* Force CASE to have just one word */
2995 if (ctx->ctx_res_w == RES_CASE) {
2996 done_pipe(ctx, PIPE_SEQ);
2997 }
2998#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00002999
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003000 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003001
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003002 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003003 return 0;
3004}
3005
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003006
3007/* Peek ahead in the input to find out if we have a "&n" construct,
3008 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003009 * Return:
3010 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3011 * REDIRFD_SYNTAX_ERR if syntax error,
3012 * REDIRFD_TO_FILE if no & was seen,
3013 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003014 */
3015#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003016#define parse_redir_right_fd(as_string, input) \
3017 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003018#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003019static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003020{
3021 int ch, d, ok;
3022
3023 ch = i_peek(input);
3024 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003025 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003026
3027 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003028 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003029 ch = i_peek(input);
3030 if (ch == '-') {
3031 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003032 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003033 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003034 }
3035 d = 0;
3036 ok = 0;
3037 while (ch != EOF && isdigit(ch)) {
3038 d = d*10 + (ch-'0');
3039 ok = 1;
3040 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003041 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003042 ch = i_peek(input);
3043 }
3044 if (ok) return d;
3045
3046//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3047
3048 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003049 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003050}
3051
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003052/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003053 */
3054static int parse_redirect(struct parse_context *ctx,
3055 int fd,
3056 redir_type style,
3057 struct in_str *input)
3058{
3059 struct command *command = ctx->command;
3060 struct redir_struct *redir;
3061 struct redir_struct **redirp;
3062 int dup_num;
3063
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003064 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003065 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003066 /* Check for a '>&1' type redirect */
3067 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3068 if (dup_num == REDIRFD_SYNTAX_ERR)
3069 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003070 } else {
3071 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003072 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003073 if (dup_num) { /* <<-... */
3074 ch = i_getch(input);
3075 nommu_addchr(&ctx->as_string, ch);
3076 ch = i_peek(input);
3077 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003078 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003079
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003080 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003081 int ch = i_peek(input);
3082 if (ch == '|') {
3083 /* >|FILE redirect ("clobbering" >).
3084 * Since we do not support "set -o noclobber" yet,
3085 * >| and > are the same for now. Just eat |.
3086 */
3087 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003088 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003089 }
3090 }
3091
3092 /* Create a new redir_struct and append it to the linked list */
3093 redirp = &command->redirects;
3094 while ((redir = *redirp) != NULL) {
3095 redirp = &(redir->next);
3096 }
3097 *redirp = redir = xzalloc(sizeof(*redir));
3098 /* redir->next = NULL; */
3099 /* redir->rd_filename = NULL; */
3100 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003101 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003102
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003103 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3104 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003105
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003106 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003107 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003108 /* Erik had a check here that the file descriptor in question
3109 * is legit; I postpone that to "run time"
3110 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003111 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3112 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003113 } else {
3114 /* Set ctx->pending_redirect, so we know what to do at the
3115 * end of the next parsed word. */
3116 ctx->pending_redirect = redir;
3117 }
3118 return 0;
3119}
3120
Eric Andersen25f27032001-04-26 23:22:31 +00003121/* If a redirect is immediately preceded by a number, that number is
3122 * supposed to tell which file descriptor to redirect. This routine
3123 * looks for such preceding numbers. In an ideal world this routine
3124 * needs to handle all the following classes of redirects...
3125 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3126 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3127 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3128 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003129 *
3130 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3131 * "2.7 Redirection
3132 * ... If n is quoted, the number shall not be recognized as part of
3133 * the redirection expression. For example:
3134 * echo \2>a
3135 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003136 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003137 *
3138 * A -1 return means no valid number was found,
3139 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003140 */
3141static int redirect_opt_num(o_string *o)
3142{
3143 int num;
3144
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003145 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003146 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003147 num = bb_strtou(o->data, NULL, 10);
3148 if (errno || num < 0)
3149 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003150 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003151 return num;
3152}
3153
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003154#if BB_MMU
3155#define fetch_till_str(as_string, input, word, skip_tabs) \
3156 fetch_till_str(input, word, skip_tabs)
3157#endif
3158static char *fetch_till_str(o_string *as_string,
3159 struct in_str *input,
3160 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003161 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003162{
3163 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003164 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003165 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003166 int ch;
3167
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003168 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003169 while (1) {
3170 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003171 if (ch != EOF)
3172 nommu_addchr(as_string, ch);
3173 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003174 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3175 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003176 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3177 heredoc.data[past_EOL] = '\0';
3178 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3179 return heredoc.data;
3180 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003181 while (ch == '\n') {
3182 o_addchr(&heredoc, ch);
3183 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003184 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003185 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003186 do {
3187 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003188 if (ch != EOF)
3189 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003190 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003191 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003192 }
3193 if (ch == EOF) {
3194 o_free_unsafe(&heredoc);
3195 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003196 }
3197 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003198 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003199 if (prev == '\\' && ch == '\\')
3200 /* Correctly handle foo\\<eol> (not a line cont.) */
3201 prev = 0; /* not \ */
3202 else
3203 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003204 }
3205}
3206
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003207/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3208 * and load them all. There should be exactly heredoc_cnt of them.
3209 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003210static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3211{
3212 struct pipe *pi = ctx->list_head;
3213
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003214 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003215 int i;
3216 struct command *cmd = pi->cmds;
3217
3218 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3219 pi->num_cmds,
3220 cmd->argv ? cmd->argv[0] : "NONE");
3221 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003222 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003223
3224 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3225 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003226 while (redir) {
3227 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003228 char *p;
3229
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003230 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003231 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003232 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003233 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003234 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003235 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003236 return 1;
3237 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003238 free(redir->rd_filename);
3239 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003240 heredoc_cnt--;
3241 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003242 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003243 }
3244 cmd++;
3245 }
3246 pi = pi->next;
3247 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003248#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003249 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003250 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003251 bb_error_msg_and_die("heredoc BUG 2");
3252#endif
3253 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003254}
3255
3256
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003257static int run_list(struct pipe *pi);
3258#if BB_MMU
3259#define parse_stream(pstring, input, end_trigger) \
3260 parse_stream(input, end_trigger)
3261#endif
3262static struct pipe *parse_stream(char **pstring,
3263 struct in_str *input,
3264 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003265
Eric Andersen25f27032001-04-26 23:22:31 +00003266
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003267#if !ENABLE_HUSH_FUNCTIONS
3268#define parse_group(dest, ctx, input, ch) \
3269 parse_group(ctx, input, ch)
3270#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003271static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003272 struct in_str *input, int ch)
3273{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003274 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003275 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003276 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003277 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003278 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003279 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003280
3281 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003282#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003283 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003284 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003285 if (done_word(dest, ctx))
3286 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003287 if (!command->argv)
3288 goto skip; /* (... */
3289 if (command->argv[1]) { /* word word ... (... */
3290 syntax_error_unexpected_ch('(');
3291 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003292 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003293 /* it is "word(..." or "word (..." */
3294 do
3295 ch = i_getch(input);
3296 while (ch == ' ' || ch == '\t');
3297 if (ch != ')') {
3298 syntax_error_unexpected_ch(ch);
3299 return 1;
3300 }
3301 nommu_addchr(&ctx->as_string, ch);
3302 do
3303 ch = i_getch(input);
3304 while (ch == ' ' || ch == '\t' || ch == '\n');
3305 if (ch != '{') {
3306 syntax_error_unexpected_ch(ch);
3307 return 1;
3308 }
3309 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003310 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003311 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003312 }
3313#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003314
3315#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003316 if (command->argv /* word [word]{... */
3317 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003318 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003319 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003320 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003321 debug_printf_parse("parse_group return 1: "
3322 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003323 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003324 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003325#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003326
3327#if ENABLE_HUSH_FUNCTIONS
3328 skip:
3329#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003330 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003331 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003332 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003333 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003334 } else {
3335 /* bash does not allow "{echo...", requires whitespace */
3336 ch = i_getch(input);
3337 if (ch != ' ' && ch != '\t' && ch != '\n') {
3338 syntax_error_unexpected_ch(ch);
3339 return 1;
3340 }
3341 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003342 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003343
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003344 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003345#if BB_MMU
3346# define as_string NULL
3347#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003348 char *as_string = NULL;
3349#endif
3350 pipe_list = parse_stream(&as_string, input, endch);
3351#if !BB_MMU
3352 if (as_string)
3353 o_addstr(&ctx->as_string, as_string);
3354#endif
3355 /* empty ()/{} or parse error? */
3356 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003357 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003358 if (!BB_MMU)
3359 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003360 debug_printf_parse("parse_group return 1: "
3361 "parse_stream returned %p\n", pipe_list);
3362 return 1;
3363 }
3364 command->group = pipe_list;
3365#if !BB_MMU
3366 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3367 command->group_as_string = as_string;
3368 debug_printf_parse("end of group, remembering as:'%s'\n",
3369 command->group_as_string);
3370#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003371#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003372 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003373 debug_printf_parse("parse_group return 0\n");
3374 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003375 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003376}
3377
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003378#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003379/* Subroutines for copying $(...) and `...` things */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003380static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003381/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003382static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003383{
3384 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003385 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003386 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003387 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003388 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003389 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003390 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003391 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003392 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003393 }
3394}
3395/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003396static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003397{
3398 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003399 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003400 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003401 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003402 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003403 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003404 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003405 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003406 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003407 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003408 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003409 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003410 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003411 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003412 add_till_backquote(dest, input, /*in_dquote:*/ 1);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003413 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003414 continue;
3415 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003416 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003417 }
3418}
3419/* Process `cmd` - copy contents until "`" is seen. Complicated by
3420 * \` quoting.
3421 * "Within the backquoted style of command substitution, backslash
3422 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3423 * The search for the matching backquote shall be satisfied by the first
3424 * backquote found without a preceding backslash; during this search,
3425 * if a non-escaped backquote is encountered within a shell comment,
3426 * a here-document, an embedded command substitution of the $(command)
3427 * form, or a quoted string, undefined results occur. A single-quoted
3428 * or double-quoted string that begins, but does not end, within the
3429 * "`...`" sequence produces undefined results."
3430 * Example Output
3431 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3432 */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003433static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003434{
3435 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003436 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003437 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003438 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003439 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003440 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3441 ch = i_getch(input);
3442 if (ch != '`'
3443 && ch != '$'
3444 && ch != '\\'
3445 && (!in_dquote || ch != '"')
3446 ) {
3447 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003448 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003449 }
3450 if (ch == EOF) {
3451 syntax_error_unterm_ch('`');
3452 /*xfunc_die(); - redundant */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003453 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003454 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003455 }
3456}
3457/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3458 * quoting and nested ()s.
3459 * "With the $(command) style of command substitution, all characters
3460 * following the open parenthesis to the matching closing parenthesis
3461 * constitute the command. Any valid shell script can be used for command,
3462 * except a script consisting solely of redirections which produces
3463 * unspecified results."
3464 * Example Output
3465 * echo $(echo '(TEST)' BEST) (TEST) BEST
3466 * echo $(echo 'TEST)' BEST) TEST) BEST
3467 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003468 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003469 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003470 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003471 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3472 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003473 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003474#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003475static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003476{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003477 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003478 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003479# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003480 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003481# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003482 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3483
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003484 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003485 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003486 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003487 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003488 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003489 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003490 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003491 if (!dbl)
3492 break;
3493 /* we look for closing )) of $((EXPR)) */
3494 if (i_peek(input) == end_ch) {
3495 i_getch(input); /* eat second ')' */
3496 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003497 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003498 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003499 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003500 if (ch == '(' || ch == '{') {
3501 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003502 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003503 o_addchr(dest, ch);
3504 continue;
3505 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003506 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003507 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003508 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003509 continue;
3510 }
3511 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003512 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003513 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003514 continue;
3515 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003516 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003517 add_till_backquote(dest, input, /*in_dquote:*/ 0);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003518 o_addchr(dest, ch);
3519 continue;
3520 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003521 if (ch == '\\') {
3522 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003523 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003524 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003525 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003526 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003527 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003528 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003529 continue;
3530 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003531 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003532 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003533}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003534#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003535
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003536/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003537#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003538#define parse_dollar(as_string, dest, input, quote_mask) \
3539 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003540#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003541#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003542static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003543 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003544 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003545{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003546 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003547
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003548 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003549 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003550 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003551 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003552 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003553 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003554 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003555 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003556 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003557 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003558 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003559 if (!isalnum(ch) && ch != '_')
3560 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003561 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003562 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003563 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003564 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003565 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003566 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003567 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003568 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003569 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003570 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003571 o_addchr(dest, ch | quote_mask);
3572 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003573 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003574 case '$': /* pid */
3575 case '!': /* last bg pid */
3576 case '?': /* last exit code */
3577 case '#': /* number of args */
3578 case '*': /* args */
3579 case '@': /* args */
3580 goto make_one_char_var;
3581 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003582 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3583
Denys Vlasenko74369502010-05-21 19:52:01 +02003584 ch = i_getch(input); /* eat '{' */
3585 nommu_addchr(as_string, ch);
3586
3587 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003588 /* It should be ${?}, or ${#var},
3589 * or even ${?+subst} - operator acting on a special variable,
3590 * or the beginning of variable name.
3591 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003592 if (ch == EOF
3593 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3594 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003595 bad_dollar_syntax:
3596 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003597 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003598 return 1;
3599 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003600 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003601 ch |= quote_mask;
3602
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003603 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003604 * However, this regresses some of our testsuite cases
3605 * which check invalid constructs like ${%}.
3606 * Oh well... let's check that the var name part is fine... */
3607
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003608 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003609 unsigned pos;
3610
Denys Vlasenko74369502010-05-21 19:52:01 +02003611 o_addchr(dest, ch);
3612 debug_printf_parse(": '%c'\n", ch);
3613
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003614 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003615 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003616 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003617 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003618
Denys Vlasenko74369502010-05-21 19:52:01 +02003619 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003620 unsigned end_ch;
3621 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003622 /* handle parameter expansions
3623 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3624 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003625 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003626 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003627
3628 /* Eat everything until closing '}' (or ':') */
3629 end_ch = '}';
3630 if (ENABLE_HUSH_BASH_COMPAT
3631 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003632 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003633 ) {
3634 /* It's ${var:N[:M]} thing */
3635 end_ch = '}' * 0x100 + ':';
3636 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003637 if (ENABLE_HUSH_BASH_COMPAT
3638 && ch == '/'
3639 ) {
3640 /* It's ${var/[/]pattern[/repl]} thing */
3641 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3642 i_getch(input);
3643 nommu_addchr(as_string, '/');
3644 ch = '\\';
3645 }
3646 end_ch = '}' * 0x100 + '/';
3647 }
3648 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003649 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003650 if (!BB_MMU)
3651 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003652#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003653 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003654#else
3655#error Simple code to only allow ${var} is not implemented
3656#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003657 if (as_string) {
3658 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003659 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003660 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003661
3662 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3663 /* close the first block: */
3664 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003665 /* while parsing N from ${var:N[:M]}
3666 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003667 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003668 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003669 end_ch = '}';
3670 goto again;
3671 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003672 /* got '}' */
3673 if (end_ch == '}' * 0x100 + ':') {
3674 /* it's ${var:N} - emulate :999999999 */
3675 o_addstr(dest, "999999999");
3676 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003677 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003678 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003679 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003680 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003681 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3682 break;
3683 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003684#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003685 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003686 unsigned pos;
3687
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003688 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003689 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003690# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003691 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003692 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003693 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003694 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3695 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003696 if (!BB_MMU)
3697 pos = dest->length;
3698 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003699 if (as_string) {
3700 o_addstr(as_string, dest->data + pos);
3701 o_addchr(as_string, ')');
3702 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003703 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003704 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003705 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003706 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003707# endif
3708# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003709 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3710 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003711 if (!BB_MMU)
3712 pos = dest->length;
3713 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003714 if (as_string) {
3715 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003716 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003717 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003718 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003719# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003720 break;
3721 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003722#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003723 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003724 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003725 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003726 ch = i_peek(input);
3727 if (isalnum(ch)) { /* it's $_name or $_123 */
3728 ch = '_';
3729 goto make_var;
3730 }
3731 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003732 /* TODO: $_ and $-: */
3733 /* $_ Shell or shell script name; or last argument of last command
3734 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3735 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003736 /* $- Option flags set by set builtin or shell options (-i etc) */
3737 default:
3738 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003739 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003740 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003741 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003742#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003743}
3744
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003745#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003746# if ENABLE_HUSH_BASH_COMPAT
3747#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3748 encode_string(dest, input, dquote_end, process_bkslash)
3749# else
3750/* only ${var/pattern/repl} (its pattern part) needs additional mode */
3751#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3752 encode_string(dest, input, dquote_end)
3753# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003754#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003755
3756#else /* !MMU */
3757
3758# if ENABLE_HUSH_BASH_COMPAT
3759/* all parameters are needed, no macro tricks */
3760# else
3761#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3762 encode_string(as_string, dest, input, dquote_end)
3763# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003764#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003765static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003766 o_string *dest,
3767 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02003768 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003769 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003770{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003771#if !ENABLE_HUSH_BASH_COMPAT
3772 const int process_bkslash = 1;
3773#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003774 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003775 int next;
3776
3777 again:
3778 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003779 if (ch != EOF)
3780 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003781 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003782 debug_printf_parse("encode_string return 0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003783 return 0;
3784 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003785 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003786 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003787 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003788 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003789 }
3790 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003791 if (ch != '\n') {
3792 next = i_peek(input);
3793 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003794 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003795 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003796 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003797 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003798 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003799 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003800 }
3801 /* bash:
3802 * "The backslash retains its special meaning [in "..."]
3803 * only when followed by one of the following characters:
3804 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003805 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003806 * NB: in (unquoted) heredoc, above does not apply to ",
3807 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003808 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003809 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003810 ch = i_getch(input); /* eat next */
3811 if (ch == '\n')
3812 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02003813 } /* else: ch remains == '\\', and we double it below: */
3814 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003815 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003816 goto again;
3817 }
3818 if (ch == '$') {
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003819 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003820 debug_printf_parse("encode_string return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003821 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003822 return 1;
3823 }
3824 goto again;
3825 }
3826#if ENABLE_HUSH_TICK
3827 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003828 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003829 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3830 o_addchr(dest, 0x80 | '`');
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003831 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003832 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3833 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003834 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003835 }
3836#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003837 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003838 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003839#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003840}
3841
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003842/*
3843 * Scan input until EOF or end_trigger char.
3844 * Return a list of pipes to execute, or NULL on EOF
3845 * or if end_trigger character is met.
3846 * On syntax error, exit is shell is not interactive,
3847 * reset parsing machinery and start parsing anew,
3848 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003849 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003850static struct pipe *parse_stream(char **pstring,
3851 struct in_str *input,
3852 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003853{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003854 struct parse_context ctx;
3855 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003856 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00003857
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003858 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003859 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003860 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003861 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02003862 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003863 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003864
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003865 /* If very first arg is "" or '', dest.data may end up NULL.
3866 * Preventing this: */
3867 o_addchr(&dest, '\0');
3868 dest.length = 0;
3869
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003870 /* We used to separate words on $IFS here. This was wrong.
3871 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003872 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003873 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003874
3875 reset: /* we come back here only on syntax errors in interactive shell */
3876
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003877#if ENABLE_HUSH_INTERACTIVE
3878 input->promptmode = 0; /* PS1 */
3879#endif
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003880 if (MAYBE_ASSIGNMENT != 0)
3881 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003882 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003883 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003884 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003885 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003886 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003887 int ch;
3888 int next;
3889 int redir_fd;
3890 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003891
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003892 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003893 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003894 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003895 if (ch == EOF) {
3896 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003897
3898 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003899 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003900 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003901 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003902 /* end_trigger == '}' case errors out earlier,
3903 * checking only ')' */
3904 if (end_trigger == ')') {
3905 syntax_error_unterm_ch('('); /* exits */
3906 /* goto parse_error; */
3907 }
3908
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003909 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02003910 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003911 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003912 o_free(&dest);
3913 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003914 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003915 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003916 /* (this makes bare "&" cmd a no-op.
3917 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003918 if (pi->num_cmds == 0
3919 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3920 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003921 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003922 pi = NULL;
3923 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003924#if !BB_MMU
3925 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3926 if (pstring)
3927 *pstring = ctx.as_string.data;
3928 else
3929 o_free_unsafe(&ctx.as_string);
3930#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003931 debug_leave();
3932 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003933 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003934 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003935 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003936
3937 next = '\0';
3938 if (ch != '\n')
3939 next = i_peek(input);
3940
3941 is_special = "{}<>;&|()#'" /* special outside of "str" */
3942 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3943 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003944 if (ctx.command->argv /* word [word]{... - non-special */
3945 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003946 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003947 || (next != ';' /* }; - special */
3948 && next != ')' /* }) - special */
3949 && next != '&' /* }& and }&& ... - special */
3950 && next != '|' /* }|| ... - special */
3951 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02003952 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003953 ) {
3954 /* They are not special, skip "{}" */
3955 is_special += 2;
3956 }
3957 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003958 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003959
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003960 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003961 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003962 o_addQchr(&dest, ch);
3963 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3964 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003965 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003966 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00003967 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003968 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003969 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003970 continue;
3971 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00003972
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003973 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003974 if (done_word(&dest, &ctx)) {
3975 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00003976 }
Denis Vlasenko37181682009-04-03 03:19:15 +00003977 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003978#if ENABLE_HUSH_CASE
3979 /* "case ... in <newline> word) ..." -
3980 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003981 if (ctx.command->argv == NULL
3982 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00003983 ) {
3984 continue;
3985 }
3986#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003987 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003988 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003989 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3990 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003991 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003992 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003993 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003994 heredoc_cnt = 0;
3995 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003996 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003997 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003998 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003999 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004000 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004001 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004002
4003 /* "cmd}" or "cmd }..." without semicolon or &:
4004 * } is an ordinary char in this case, even inside { cmd; }
4005 * Pathological example: { ""}; } should exec "}" cmd
4006 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004007 if (ch == '}') {
4008 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4009 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004010 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004011 ) {
4012 goto ordinary_char;
4013 }
4014 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4015 goto skip_end_trigger;
4016 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004017 }
4018
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004019 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004020 && (ch != ';' || heredoc_cnt == 0)
4021#if ENABLE_HUSH_CASE
4022 && (ch != ')'
4023 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004024 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004025 )
4026#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004027 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004028 if (heredoc_cnt) {
4029 /* This is technically valid:
4030 * { cat <<HERE; }; echo Ok
4031 * heredoc
4032 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004033 * HERE
4034 * but we don't support this.
4035 * We require heredoc to be in enclosing {}/(),
4036 * if any.
4037 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004038 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004039 goto parse_error;
4040 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004041 if (done_word(&dest, &ctx)) {
4042 goto parse_error;
4043 }
4044 done_pipe(&ctx, PIPE_SEQ);
4045 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004046 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004047 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004048 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004049 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004050 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004051#if !BB_MMU
4052 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4053 if (pstring)
4054 *pstring = ctx.as_string.data;
4055 else
4056 o_free_unsafe(&ctx.as_string);
4057#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004058 debug_leave();
4059 debug_printf_parse("parse_stream return %p: "
4060 "end_trigger char found\n",
4061 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004062 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004063 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004064 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004065 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004066 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004067 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004068
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004069 /* Catch <, > before deciding whether this word is
4070 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4071 switch (ch) {
4072 case '>':
4073 redir_fd = redirect_opt_num(&dest);
4074 if (done_word(&dest, &ctx)) {
4075 goto parse_error;
4076 }
4077 redir_style = REDIRECT_OVERWRITE;
4078 if (next == '>') {
4079 redir_style = REDIRECT_APPEND;
4080 ch = i_getch(input);
4081 nommu_addchr(&ctx.as_string, ch);
4082 }
4083#if 0
4084 else if (next == '(') {
4085 syntax_error(">(process) not supported");
4086 goto parse_error;
4087 }
4088#endif
4089 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4090 goto parse_error;
4091 continue; /* back to top of while (1) */
4092 case '<':
4093 redir_fd = redirect_opt_num(&dest);
4094 if (done_word(&dest, &ctx)) {
4095 goto parse_error;
4096 }
4097 redir_style = REDIRECT_INPUT;
4098 if (next == '<') {
4099 redir_style = REDIRECT_HEREDOC;
4100 heredoc_cnt++;
4101 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4102 ch = i_getch(input);
4103 nommu_addchr(&ctx.as_string, ch);
4104 } else if (next == '>') {
4105 redir_style = REDIRECT_IO;
4106 ch = i_getch(input);
4107 nommu_addchr(&ctx.as_string, ch);
4108 }
4109#if 0
4110 else if (next == '(') {
4111 syntax_error("<(process) not supported");
4112 goto parse_error;
4113 }
4114#endif
4115 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4116 goto parse_error;
4117 continue; /* back to top of while (1) */
4118 }
4119
4120 if (dest.o_assignment == MAYBE_ASSIGNMENT
4121 /* check that we are not in word in "a=1 2>word b=1": */
4122 && !ctx.pending_redirect
4123 ) {
4124 /* ch is a special char and thus this word
4125 * cannot be an assignment */
4126 dest.o_assignment = NOT_ASSIGNMENT;
4127 }
4128
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004129 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4130
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004131 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00004132 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004133 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004134 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004135 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004136 if (ch == EOF || ch == '\n')
4137 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004138 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004139 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004140 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004141 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00004142 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004143 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004144 }
4145 break;
4146 case '\\':
4147 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004148 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004149 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004150 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004151 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004152 if (ch != '\n') {
4153 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004154 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004155 o_addchr(&dest, ch);
4156 nommu_addchr(&ctx.as_string, ch);
4157 /* Example: echo Hello \2>file
4158 * we need to know that word 2 is quoted */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004159 dest.has_quoted_part = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004160 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004161#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004162 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004163 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4164 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02004165 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02004166#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004167 break;
4168 case '$':
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004169 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004170 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004171 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004172 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004173 }
Eric Andersen25f27032001-04-26 23:22:31 +00004174 break;
4175 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004176 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004177 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004178 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004179 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004180 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004181 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004182 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004183 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004184 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004185 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004186 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004187 }
Eric Andersen25f27032001-04-26 23:22:31 +00004188 break;
4189 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004190 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004191 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004192 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004193 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004194 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004195 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004196 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004197#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004198 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004199 unsigned pos;
4200
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004201 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4202 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004203 pos = dest.length;
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004204 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004205# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004206 o_addstr(&ctx.as_string, dest.data + pos);
4207 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004208# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004209 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4210 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004211 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004212 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004213#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004214 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004215#if ENABLE_HUSH_CASE
4216 case_semi:
4217#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004218 if (done_word(&dest, &ctx)) {
4219 goto parse_error;
4220 }
4221 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004222#if ENABLE_HUSH_CASE
4223 /* Eat multiple semicolons, detect
4224 * whether it means something special */
4225 while (1) {
4226 ch = i_peek(input);
4227 if (ch != ';')
4228 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004229 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004230 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004231 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004232 ctx.ctx_dsemicolon = 1;
4233 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004234 break;
4235 }
4236 }
4237#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004238 new_cmd:
4239 /* We just finished a cmd. New one may start
4240 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004241 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004242 break;
4243 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004244 if (done_word(&dest, &ctx)) {
4245 goto parse_error;
4246 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004247 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004248 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004249 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004250 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004251 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004252 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004253 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004254 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004255 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004256 if (done_word(&dest, &ctx)) {
4257 goto parse_error;
4258 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004259#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004260 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004261 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004262#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004263 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004264 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004265 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004266 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004267 } else {
4268 /* we could pick up a file descriptor choice here
4269 * with redirect_opt_num(), but bash doesn't do it.
4270 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004271 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004272#if !BB_MMU
4273 o_reset_to_empty_unquoted(&ctx.as_string);
4274#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004275 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004276 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004277 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004278#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004279 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004280 if (ctx.ctx_res_w == RES_MATCH
4281 && ctx.command->argv == NULL /* not (word|(... */
4282 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004283 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004284 ) {
4285 continue;
4286 }
4287#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004288 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004289 if (parse_group(&dest, &ctx, input, ch) != 0) {
4290 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004291 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004292 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004293 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004294#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004295 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004296 goto case_semi;
4297#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004298 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004299 /* proper use of this character is caught by end_trigger:
4300 * if we see {, we call parse_group(..., end_trigger='}')
4301 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004302 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004303 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004304 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004305 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004306 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004307 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004308 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004309
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004310 parse_error:
4311 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004312 struct parse_context *pctx;
4313 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004314
4315 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004316 * Sample for finding leaks on syntax error recovery path.
4317 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004318 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004319 * Samples to catch leaks at execution:
4320 * while if (true | {true;}); then echo ok; fi; do break; done
4321 * 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 +00004322 */
4323 pctx = &ctx;
4324 do {
4325 /* Update pipe/command counts,
4326 * otherwise freeing may miss some */
4327 done_pipe(pctx, PIPE_SEQ);
4328 debug_printf_clean("freeing list %p from ctx %p\n",
4329 pctx->list_head, pctx);
4330 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004331 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004332 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004333#if !BB_MMU
4334 o_free_unsafe(&pctx->as_string);
4335#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004336 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004337 if (pctx != &ctx) {
4338 free(pctx);
4339 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004340 IF_HAS_KEYWORDS(pctx = p2;)
4341 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004342 /* Free text, clear all dest fields */
4343 o_free(&dest);
4344 /* If we are not in top-level parse, we return,
4345 * our caller will propagate error.
4346 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004347 if (end_trigger != ';') {
4348#if !BB_MMU
4349 if (pstring)
4350 *pstring = NULL;
4351#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004352 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004353 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004354 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004355 /* Discard cached input, force prompt */
4356 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004357 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004358 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004359 }
Eric Andersen25f27032001-04-26 23:22:31 +00004360}
4361
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004362
4363/*** Execution routines ***/
4364
4365/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004366#if !ENABLE_HUSH_BASH_COMPAT
4367/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4368#define expand_string_to_string(str, do_unbackslash) \
4369 expand_string_to_string(str)
4370#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004371static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004372static int process_command_subs(o_string *dest, const char *s);
4373
4374/* expand_strvec_to_strvec() takes a list of strings, expands
4375 * all variable references within and returns a pointer to
4376 * a list of expanded strings, possibly with larger number
4377 * of strings. (Think VAR="a b"; echo $VAR).
4378 * This new list is allocated as a single malloc block.
4379 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004380 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004381 * Caller can deallocate entire list by single free(list). */
4382
4383/* Store given string, finalizing the word and starting new one whenever
4384 * we encounter IFS char(s). This is used for expanding variable values.
4385 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4386static int expand_on_ifs(o_string *output, int n, const char *str)
4387{
4388 while (1) {
4389 int word_len = strcspn(str, G.ifs);
4390 if (word_len) {
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004391 if (!(output->o_expflags & EXP_FLAG_GLOB))
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004392 o_addblock(output, str, word_len);
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004393 else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004394 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004395 * Example: "v='\*'; echo b$v" prints "b\*"
4396 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004397 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004398 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004399 /*/ Why can't we do it easier? */
4400 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4401 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4402 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004403 str += word_len;
4404 }
4405 if (!*str) /* EOL - do not finalize word */
4406 break;
4407 o_addchr(output, '\0');
4408 debug_print_list("expand_on_ifs", output, n);
4409 n = o_save_ptr(output, n);
4410 str += strspn(str, G.ifs); /* skip ifs chars */
4411 }
4412 debug_print_list("expand_on_ifs[1]", output, n);
4413 return n;
4414}
4415
4416/* Helper to expand $((...)) and heredoc body. These act as if
4417 * they are in double quotes, with the exception that they are not :).
4418 * Just the rules are similar: "expand only $var and `cmd`"
4419 *
4420 * Returns malloced string.
4421 * As an optimization, we return NULL if expansion is not needed.
4422 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004423#if !ENABLE_HUSH_BASH_COMPAT
4424/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4425#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4426 encode_then_expand_string(str)
4427#endif
4428static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004429{
4430 char *exp_str;
4431 struct in_str input;
4432 o_string dest = NULL_O_STRING;
4433
4434 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004435 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004436#if ENABLE_HUSH_TICK
4437 && !strchr(str, '`')
4438#endif
4439 ) {
4440 return NULL;
4441 }
4442
4443 /* We need to expand. Example:
4444 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4445 */
4446 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004447 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004448 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004449 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004450 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4451 o_free_unsafe(&dest);
4452 return exp_str;
4453}
4454
4455#if ENABLE_SH_MATH_SUPPORT
4456static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
4457{
4458 arith_eval_hooks_t hooks;
4459 arith_t res;
4460 char *exp_str;
4461
4462 hooks.lookupvar = get_local_var_value;
4463 hooks.setvar = set_local_var_from_halves;
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02004464 //hooks.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004465 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004466 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
4467 free(exp_str);
4468 return res;
4469}
4470#endif
4471
4472#if ENABLE_HUSH_BASH_COMPAT
4473/* ${var/[/]pattern[/repl]} helpers */
4474static char *strstr_pattern(char *val, const char *pattern, int *size)
4475{
4476 while (1) {
4477 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4478 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4479 if (end) {
4480 *size = end - val;
4481 return val;
4482 }
4483 if (*val == '\0')
4484 return NULL;
4485 /* Optimization: if "*pat" did not match the start of "string",
4486 * we know that "tring", "ring" etc will not match too:
4487 */
4488 if (pattern[0] == '*')
4489 return NULL;
4490 val++;
4491 }
4492}
4493static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4494{
4495 char *result = NULL;
4496 unsigned res_len = 0;
4497 unsigned repl_len = strlen(repl);
4498
4499 while (1) {
4500 int size;
4501 char *s = strstr_pattern(val, pattern, &size);
4502 if (!s)
4503 break;
4504
4505 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4506 memcpy(result + res_len, val, s - val);
4507 res_len += s - val;
4508 strcpy(result + res_len, repl);
4509 res_len += repl_len;
4510 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4511
4512 val = s + size;
4513 if (exp_op == '/')
4514 break;
4515 }
4516 if (val[0] && result) {
4517 result = xrealloc(result, res_len + strlen(val) + 1);
4518 strcpy(result + res_len, val);
4519 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4520 }
4521 debug_printf_varexp("result:'%s'\n", result);
4522 return result;
4523}
4524#endif
4525
4526/* Helper:
4527 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4528 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004529static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004530{
4531 const char *val = NULL;
4532 char *to_be_freed = NULL;
4533 char *p = *pp;
4534 char *var;
4535 char first_char;
4536 char exp_op;
4537 char exp_save = exp_save; /* for compiler */
4538 char *exp_saveptr; /* points to expansion operator */
4539 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004540 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004541
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004542 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004543 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004544 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004545 arg0 = arg[0];
4546 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004547 exp_op = 0;
4548
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004549 if (first_char == '#' /* ${#... */
4550 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4551 ) {
4552 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004553 var++;
4554 exp_op = 'L';
4555 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004556 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004557 if (exp_saveptr /* if 2nd char is one of expansion operators */
4558 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4559 ) {
4560 /* ${?:0}, ${#[:]%0} etc */
4561 exp_saveptr = var + 1;
4562 } else {
4563 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4564 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4565 }
4566 exp_op = exp_save = *exp_saveptr;
4567 if (exp_op) {
4568 exp_word = exp_saveptr + 1;
4569 if (exp_op == ':') {
4570 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004571//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004572 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004573 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004574 ) {
4575 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4576 exp_op = ':';
4577 exp_word--;
4578 }
4579 }
4580 *exp_saveptr = '\0';
4581 } /* else: it's not an expansion op, but bare ${var} */
4582 }
4583
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004584 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004585 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004586 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004587 int n = xatoi_positive(var);
4588 if (n < G.global_argc)
4589 val = G.global_argv[n];
4590 /* else val remains NULL: $N with too big N */
4591 } else {
4592 switch (var[0]) {
4593 case '$': /* pid */
4594 val = utoa(G.root_pid);
4595 break;
4596 case '!': /* bg pid */
4597 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4598 break;
4599 case '?': /* exitcode */
4600 val = utoa(G.last_exitcode);
4601 break;
4602 case '#': /* argc */
4603 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4604 break;
4605 default:
4606 val = get_local_var_value(var);
4607 }
4608 }
4609
4610 /* Handle any expansions */
4611 if (exp_op == 'L') {
4612 debug_printf_expand("expand: length(%s)=", val);
4613 val = utoa(val ? strlen(val) : 0);
4614 debug_printf_expand("%s\n", val);
4615 } else if (exp_op) {
4616 if (exp_op == '%' || exp_op == '#') {
4617 /* Standard-mandated substring removal ops:
4618 * ${parameter%word} - remove smallest suffix pattern
4619 * ${parameter%%word} - remove largest suffix pattern
4620 * ${parameter#word} - remove smallest prefix pattern
4621 * ${parameter##word} - remove largest prefix pattern
4622 *
4623 * Word is expanded to produce a glob pattern.
4624 * Then var's value is matched to it and matching part removed.
4625 */
4626 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004627 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004628 char *exp_exp_word;
4629 char *loc;
4630 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4631 if (exp_op == *exp_word) /* ## or %% */
4632 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004633 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004634 if (exp_exp_word)
4635 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004636 /* HACK ALERT. We depend here on the fact that
4637 * G.global_argv and results of utoa and get_local_var_value
4638 * are actually in writable memory:
4639 * scan_and_match momentarily stores NULs there. */
4640 t = (char*)val;
4641 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004642 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004643 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004644 free(exp_exp_word);
4645 if (loc) { /* match was found */
4646 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004647 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004648 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004649 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004650 }
4651 }
4652 }
4653#if ENABLE_HUSH_BASH_COMPAT
4654 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004655 /* It's ${var/[/]pattern[/repl]} thing.
4656 * Note that in encoded form it has TWO parts:
4657 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02004658 * and if // is used, it is encoded as \:
4659 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004660 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004661 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004662 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004663 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004664 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004665 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004666 * by the usual expansion rules:
4667 * >az; >bz;
4668 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4669 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4670 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4671 * v='a bz'; echo ${v/a*z/\z} prints "z"
4672 * (note that a*z _pattern_ is never globbed!)
4673 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004674 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004675 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004676 if (!pattern)
4677 pattern = xstrdup(exp_word);
4678 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4679 *p++ = SPECIAL_VAR_SYMBOL;
4680 exp_word = p;
4681 p = strchr(p, SPECIAL_VAR_SYMBOL);
4682 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004683 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004684 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4685 /* HACK ALERT. We depend here on the fact that
4686 * G.global_argv and results of utoa and get_local_var_value
4687 * are actually in writable memory:
4688 * replace_pattern momentarily stores NULs there. */
4689 t = (char*)val;
4690 to_be_freed = replace_pattern(t,
4691 pattern,
4692 (repl ? repl : exp_word),
4693 exp_op);
4694 if (to_be_freed) /* at least one replace happened */
4695 val = to_be_freed;
4696 free(pattern);
4697 free(repl);
4698 }
4699 }
4700#endif
4701 else if (exp_op == ':') {
4702#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4703 /* It's ${var:N[:M]} bashism.
4704 * Note that in encoded form it has TWO parts:
4705 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4706 */
4707 arith_t beg, len;
4708 int errcode = 0;
4709
4710 beg = expand_and_evaluate_arith(exp_word, &errcode);
4711 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4712 *p++ = SPECIAL_VAR_SYMBOL;
4713 exp_word = p;
4714 p = strchr(p, SPECIAL_VAR_SYMBOL);
4715 *p = '\0';
4716 len = expand_and_evaluate_arith(exp_word, &errcode);
4717 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4718
4719 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
4720 if (beg < 0) /* bash compat */
4721 beg = 0;
4722 debug_printf_varexp("from val:'%s'\n", val);
4723 if (len == 0 || !val || beg >= strlen(val))
4724 val = "";
4725 else {
4726 /* Paranoia. What if user entered 9999999999999
4727 * which fits in arith_t but not int? */
4728 if (len >= INT_MAX)
4729 len = INT_MAX;
4730 val = to_be_freed = xstrndup(val + beg, len);
4731 }
4732 debug_printf_varexp("val:'%s'\n", val);
4733 } else
4734#endif
4735 {
4736 die_if_script("malformed ${%s:...}", var);
4737 val = "";
4738 }
4739 } else { /* one of "-=+?" */
4740 /* Standard-mandated substitution ops:
4741 * ${var?word} - indicate error if unset
4742 * If var is unset, word (or a message indicating it is unset
4743 * if word is null) is written to standard error
4744 * and the shell exits with a non-zero exit status.
4745 * Otherwise, the value of var is substituted.
4746 * ${var-word} - use default value
4747 * If var is unset, word is substituted.
4748 * ${var=word} - assign and use default value
4749 * If var is unset, word is assigned to var.
4750 * In all cases, final value of var is substituted.
4751 * ${var+word} - use alternative value
4752 * If var is unset, null is substituted.
4753 * Otherwise, word is substituted.
4754 *
4755 * Word is subjected to tilde expansion, parameter expansion,
4756 * command substitution, and arithmetic expansion.
4757 * If word is not needed, it is not expanded.
4758 *
4759 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4760 * but also treat null var as if it is unset.
4761 */
4762 int use_word = (!val || ((exp_save == ':') && !val[0]));
4763 if (exp_op == '+')
4764 use_word = !use_word;
4765 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4766 (exp_save == ':') ? "true" : "false", use_word);
4767 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004768 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004769 if (to_be_freed)
4770 exp_word = to_be_freed;
4771 if (exp_op == '?') {
4772 /* mimic bash message */
4773 die_if_script("%s: %s",
4774 var,
4775 exp_word[0] ? exp_word : "parameter null or not set"
4776 );
4777//TODO: how interactive bash aborts expansion mid-command?
4778 } else {
4779 val = exp_word;
4780 }
4781
4782 if (exp_op == '=') {
4783 /* ${var=[word]} or ${var:=[word]} */
4784 if (isdigit(var[0]) || var[0] == '#') {
4785 /* mimic bash message */
4786 die_if_script("$%s: cannot assign in this way", var);
4787 val = NULL;
4788 } else {
4789 char *new_var = xasprintf("%s=%s", var, val);
4790 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4791 }
4792 }
4793 }
4794 } /* one of "-=+?" */
4795
4796 *exp_saveptr = exp_save;
4797 } /* if (exp_op) */
4798
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004799 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004800
4801 *pp = p;
4802 *to_be_freed_pp = to_be_freed;
4803 return val;
4804}
4805
4806/* Expand all variable references in given string, adding words to list[]
4807 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4808 * to be filled). This routine is extremely tricky: has to deal with
4809 * variables/parameters with whitespace, $* and $@, and constructs like
4810 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004811static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004812{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004813 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004814 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004815 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004816 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004817 char *p;
4818
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004819 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4820 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004821 debug_print_list("expand_vars_to_list", output, n);
4822 n = o_save_ptr(output, n);
4823 debug_print_list("expand_vars_to_list[0]", output, n);
4824
4825 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4826 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004827 char *to_be_freed = NULL;
4828 const char *val = NULL;
4829#if ENABLE_HUSH_TICK
4830 o_string subst_result = NULL_O_STRING;
4831#endif
4832#if ENABLE_SH_MATH_SUPPORT
4833 char arith_buf[sizeof(arith_t)*3 + 2];
4834#endif
4835 o_addblock(output, arg, p - arg);
4836 debug_print_list("expand_vars_to_list[1]", output, n);
4837 arg = ++p;
4838 p = strchr(p, SPECIAL_VAR_SYMBOL);
4839
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004840 /* Fetch special var name (if it is indeed one of them)
4841 * and quote bit, force the bit on if singleword expansion -
4842 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004843 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004844
4845 /* Is this variable quoted and thus expansion can't be null?
4846 * "$@" is special. Even if quoted, it can still
4847 * expand to nothing (not even an empty string),
4848 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004849 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004850 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004851
4852 switch (first_ch & 0x7f) {
4853 /* Highest bit in first_ch indicates that var is double-quoted */
4854 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004855 case '@': {
4856 int i;
4857 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004858 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004859 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004860 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004861 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004862 while (G.global_argv[i]) {
4863 n = expand_on_ifs(output, n, G.global_argv[i]);
4864 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4865 if (G.global_argv[i++][0] && G.global_argv[i]) {
4866 /* this argv[] is not empty and not last:
4867 * put terminating NUL, start new word */
4868 o_addchr(output, '\0');
4869 debug_print_list("expand_vars_to_list[2]", output, n);
4870 n = o_save_ptr(output, n);
4871 debug_print_list("expand_vars_to_list[3]", output, n);
4872 }
4873 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004874 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004875 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004876 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004877 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004878 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004879 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004880 while (1) {
4881 o_addQstr(output, G.global_argv[i]);
4882 if (++i >= G.global_argc)
4883 break;
4884 o_addchr(output, '\0');
4885 debug_print_list("expand_vars_to_list[4]", output, n);
4886 n = o_save_ptr(output, n);
4887 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004888 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004889 while (1) {
4890 o_addQstr(output, G.global_argv[i]);
4891 if (!G.global_argv[++i])
4892 break;
4893 if (G.ifs[0])
4894 o_addchr(output, G.ifs[0]);
4895 }
4896 }
4897 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004898 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004899 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4900 /* "Empty variable", used to make "" etc to not disappear */
4901 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004902 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004903 break;
4904#if ENABLE_HUSH_TICK
4905 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004906 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004907 arg++;
4908 /* Can't just stuff it into output o_string,
4909 * expanded result may need to be globbed
4910 * and $IFS-splitted */
4911 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4912 G.last_exitcode = process_command_subs(&subst_result, arg);
4913 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4914 val = subst_result.data;
4915 goto store_val;
4916#endif
4917#if ENABLE_SH_MATH_SUPPORT
4918 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4919 arith_t res;
4920 int errcode;
4921
4922 arg++; /* skip '+' */
4923 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4924 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4925 res = expand_and_evaluate_arith(arg, &errcode);
4926
4927 if (errcode < 0) {
4928 const char *msg = "error in arithmetic";
4929 switch (errcode) {
4930 case -3:
4931 msg = "exponent less than 0";
4932 break;
4933 case -2:
4934 msg = "divide by 0";
4935 break;
4936 case -5:
4937 msg = "expression recursion loop detected";
4938 break;
4939 }
4940 die_if_script(msg);
4941 }
4942 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
4943 sprintf(arith_buf, arith_t_fmt, res);
4944 val = arith_buf;
4945 break;
4946 }
4947#endif
4948 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004949 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004950 IF_HUSH_TICK(store_val:)
4951 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004952 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
4953 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004954 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004955 n = expand_on_ifs(output, n, val);
4956 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004957 }
4958 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004959 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
4960 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004961 }
4962 break;
4963
4964 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4965
4966 if (val && val[0]) {
4967 o_addQstr(output, val);
4968 }
4969 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004970
4971 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
4972 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004973 if (*p != SPECIAL_VAR_SYMBOL)
4974 *p = SPECIAL_VAR_SYMBOL;
4975
4976#if ENABLE_HUSH_TICK
4977 o_free(&subst_result);
4978#endif
4979 arg = ++p;
4980 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4981
4982 if (arg[0]) {
4983 debug_print_list("expand_vars_to_list[a]", output, n);
4984 /* this part is literal, and it was already pre-quoted
4985 * if needed (much earlier), do not use o_addQstr here! */
4986 o_addstr_with_NUL(output, arg);
4987 debug_print_list("expand_vars_to_list[b]", output, n);
4988 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004989 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004990 ) {
4991 n--;
4992 /* allow to reuse list[n] later without re-growth */
4993 output->has_empty_slot = 1;
4994 } else {
4995 o_addchr(output, '\0');
4996 }
4997
4998 return n;
4999}
5000
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005001static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005002{
5003 int n;
5004 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005005 o_string output = NULL_O_STRING;
5006
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005007 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005008
5009 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005010 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005011 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005012 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005013 }
5014 debug_print_list("expand_variables", &output, n);
5015
5016 /* output.data (malloced in one block) gets returned in "list" */
5017 list = o_finalize_list(&output, n);
5018 debug_print_strings("expand_variables[1]", list);
5019 return list;
5020}
5021
5022static char **expand_strvec_to_strvec(char **argv)
5023{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005024 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005025}
5026
5027#if ENABLE_HUSH_BASH_COMPAT
5028static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5029{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005030 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005031}
5032#endif
5033
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005034/* Used for expansion of right hand of assignments,
5035 * $((...)), heredocs, variable espansion parts.
5036 *
5037 * NB: should NOT do globbing!
5038 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5039 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005040static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005041{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005042#if !ENABLE_HUSH_BASH_COMPAT
5043 const int do_unbackslash = 1;
5044#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005045 char *argv[2], **list;
5046
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005047 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005048 /* This is generally an optimization, but it also
5049 * handles "", which otherwise trips over !list[0] check below.
5050 * (is this ever happens that we actually get str="" here?)
5051 */
5052 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5053 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005054 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005055 return xstrdup(str);
5056 }
5057
5058 argv[0] = (char*)str;
5059 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005060 list = expand_variables(argv, do_unbackslash
5061 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5062 : EXP_FLAG_SINGLEWORD
5063 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005064 if (HUSH_DEBUG)
5065 if (!list[0] || list[1])
5066 bb_error_msg_and_die("BUG in varexp2");
5067 /* actually, just move string 2*sizeof(char*) bytes back */
5068 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005069 if (do_unbackslash)
5070 unbackslash((char*)list);
5071 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005072 return (char*)list;
5073}
5074
5075/* Used for "eval" builtin */
5076static char* expand_strvec_to_string(char **argv)
5077{
5078 char **list;
5079
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005080 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005081 /* Convert all NULs to spaces */
5082 if (list[0]) {
5083 int n = 1;
5084 while (list[n]) {
5085 if (HUSH_DEBUG)
5086 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5087 bb_error_msg_and_die("BUG in varexp3");
5088 /* bash uses ' ' regardless of $IFS contents */
5089 list[n][-1] = ' ';
5090 n++;
5091 }
5092 }
5093 overlapping_strcpy((char*)list, list[0]);
5094 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5095 return (char*)list;
5096}
5097
5098static char **expand_assignments(char **argv, int count)
5099{
5100 int i;
5101 char **p;
5102
5103 G.expanded_assignments = p = NULL;
5104 /* Expand assignments into one string each */
5105 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005106 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005107 }
5108 G.expanded_assignments = NULL;
5109 return p;
5110}
5111
5112
5113#if BB_MMU
5114/* never called */
5115void re_execute_shell(char ***to_free, const char *s,
5116 char *g_argv0, char **g_argv,
5117 char **builtin_argv) NORETURN;
5118
5119static void reset_traps_to_defaults(void)
5120{
5121 /* This function is always called in a child shell
5122 * after fork (not vfork, NOMMU doesn't use this function).
5123 */
5124 unsigned sig;
5125 unsigned mask;
5126
5127 /* Child shells are not interactive.
5128 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5129 * Testcase: (while :; do :; done) + ^Z should background.
5130 * Same goes for SIGTERM, SIGHUP, SIGINT.
5131 */
5132 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5133 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5134
5135 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5136 * Stupid. It can be done with *single* &= op, but we can't use
5137 * the fact that G.blocked_set is implemented as a bitmask
5138 * in libc... */
5139 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5140 sig = 1;
5141 while (1) {
5142 if (mask & 1) {
5143 /* Careful. Only if no trap or trap is not "" */
5144 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5145 sigdelset(&G.blocked_set, sig);
5146 }
5147 mask >>= 1;
5148 if (!mask)
5149 break;
5150 sig++;
5151 }
5152 /* Our homegrown sig mask is saner to work with :) */
5153 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5154
5155 /* Resetting all traps to default except empty ones */
5156 mask = G.non_DFL_mask;
5157 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5158 if (!G.traps[sig] || !G.traps[sig][0])
5159 continue;
5160 free(G.traps[sig]);
5161 G.traps[sig] = NULL;
5162 /* There is no signal for 0 (EXIT) */
5163 if (sig == 0)
5164 continue;
5165 /* There was a trap handler, we just removed it.
5166 * But if sig still has non-DFL handling,
5167 * we should not unblock the sig. */
5168 if (mask & 1)
5169 continue;
5170 sigdelset(&G.blocked_set, sig);
5171 }
5172 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5173}
5174
5175#else /* !BB_MMU */
5176
5177static void re_execute_shell(char ***to_free, const char *s,
5178 char *g_argv0, char **g_argv,
5179 char **builtin_argv) NORETURN;
5180static void re_execute_shell(char ***to_free, const char *s,
5181 char *g_argv0, char **g_argv,
5182 char **builtin_argv)
5183{
5184# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5185 /* delims + 2 * (number of bytes in printed hex numbers) */
5186 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5187 char *heredoc_argv[4];
5188 struct variable *cur;
5189# if ENABLE_HUSH_FUNCTIONS
5190 struct function *funcp;
5191# endif
5192 char **argv, **pp;
5193 unsigned cnt;
5194 unsigned long long empty_trap_mask;
5195
5196 if (!g_argv0) { /* heredoc */
5197 argv = heredoc_argv;
5198 argv[0] = (char *) G.argv0_for_re_execing;
5199 argv[1] = (char *) "-<";
5200 argv[2] = (char *) s;
5201 argv[3] = NULL;
5202 pp = &argv[3]; /* used as pointer to empty environment */
5203 goto do_exec;
5204 }
5205
5206 cnt = 0;
5207 pp = builtin_argv;
5208 if (pp) while (*pp++)
5209 cnt++;
5210
5211 empty_trap_mask = 0;
5212 if (G.traps) {
5213 int sig;
5214 for (sig = 1; sig < NSIG; sig++) {
5215 if (G.traps[sig] && !G.traps[sig][0])
5216 empty_trap_mask |= 1LL << sig;
5217 }
5218 }
5219
5220 sprintf(param_buf, NOMMU_HACK_FMT
5221 , (unsigned) G.root_pid
5222 , (unsigned) G.root_ppid
5223 , (unsigned) G.last_bg_pid
5224 , (unsigned) G.last_exitcode
5225 , cnt
5226 , empty_trap_mask
5227 IF_HUSH_LOOPS(, G.depth_of_loop)
5228 );
5229# undef NOMMU_HACK_FMT
5230 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5231 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5232 */
5233 cnt += 6;
5234 for (cur = G.top_var; cur; cur = cur->next) {
5235 if (!cur->flg_export || cur->flg_read_only)
5236 cnt += 2;
5237 }
5238# if ENABLE_HUSH_FUNCTIONS
5239 for (funcp = G.top_func; funcp; funcp = funcp->next)
5240 cnt += 3;
5241# endif
5242 pp = g_argv;
5243 while (*pp++)
5244 cnt++;
5245 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5246 *pp++ = (char *) G.argv0_for_re_execing;
5247 *pp++ = param_buf;
5248 for (cur = G.top_var; cur; cur = cur->next) {
5249 if (strcmp(cur->varstr, hush_version_str) == 0)
5250 continue;
5251 if (cur->flg_read_only) {
5252 *pp++ = (char *) "-R";
5253 *pp++ = cur->varstr;
5254 } else if (!cur->flg_export) {
5255 *pp++ = (char *) "-V";
5256 *pp++ = cur->varstr;
5257 }
5258 }
5259# if ENABLE_HUSH_FUNCTIONS
5260 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5261 *pp++ = (char *) "-F";
5262 *pp++ = funcp->name;
5263 *pp++ = funcp->body_as_string;
5264 }
5265# endif
5266 /* We can pass activated traps here. Say, -Tnn:trap_string
5267 *
5268 * However, POSIX says that subshells reset signals with traps
5269 * to SIG_DFL.
5270 * I tested bash-3.2 and it not only does that with true subshells
5271 * of the form ( list ), but with any forked children shells.
5272 * I set trap "echo W" WINCH; and then tried:
5273 *
5274 * { echo 1; sleep 20; echo 2; } &
5275 * while true; do echo 1; sleep 20; echo 2; break; done &
5276 * true | { echo 1; sleep 20; echo 2; } | cat
5277 *
5278 * In all these cases sending SIGWINCH to the child shell
5279 * did not run the trap. If I add trap "echo V" WINCH;
5280 * _inside_ group (just before echo 1), it works.
5281 *
5282 * I conclude it means we don't need to pass active traps here.
5283 * Even if we would use signal handlers instead of signal masking
5284 * in order to implement trap handling,
5285 * exec syscall below resets signals to SIG_DFL for us.
5286 */
5287 *pp++ = (char *) "-c";
5288 *pp++ = (char *) s;
5289 if (builtin_argv) {
5290 while (*++builtin_argv)
5291 *pp++ = *builtin_argv;
5292 *pp++ = (char *) "";
5293 }
5294 *pp++ = g_argv0;
5295 while (*g_argv)
5296 *pp++ = *g_argv++;
5297 /* *pp = NULL; - is already there */
5298 pp = environ;
5299
5300 do_exec:
5301 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5302 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5303 execve(bb_busybox_exec_path, argv, pp);
5304 /* Fallback. Useful for init=/bin/hush usage etc */
5305 if (argv[0][0] == '/')
5306 execve(argv[0], argv, pp);
5307 xfunc_error_retval = 127;
5308 bb_error_msg_and_die("can't re-execute the shell");
5309}
5310#endif /* !BB_MMU */
5311
5312
5313static int run_and_free_list(struct pipe *pi);
5314
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005315/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005316 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5317 * end_trigger controls how often we stop parsing
5318 * NUL: parse all, execute, return
5319 * ';': parse till ';' or newline, execute, repeat till EOF
5320 */
5321static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005322{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005323 /* Why we need empty flag?
5324 * An obscure corner case "false; ``; echo $?":
5325 * empty command in `` should still set $? to 0.
5326 * But we can't just set $? to 0 at the start,
5327 * this breaks "false; echo `echo $?`" case.
5328 */
5329 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005330 while (1) {
5331 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005332
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005333 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005334 if (!pipe_list) { /* EOF */
5335 if (empty)
5336 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005337 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005338 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005339 debug_print_tree(pipe_list, 0);
5340 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5341 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005342 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005343 }
Eric Andersen25f27032001-04-26 23:22:31 +00005344}
5345
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005346static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005347{
5348 struct in_str input;
5349 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005350 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005351}
5352
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005353static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005354{
Eric Andersen25f27032001-04-26 23:22:31 +00005355 struct in_str input;
5356 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005357 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005358}
5359
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005360#if ENABLE_HUSH_TICK
5361static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5362{
5363 pid_t pid;
5364 int channel[2];
5365# if !BB_MMU
5366 char **to_free = NULL;
5367# endif
5368
5369 xpipe(channel);
5370 pid = BB_MMU ? xfork() : xvfork();
5371 if (pid == 0) { /* child */
5372 disable_restore_tty_pgrp_on_exit();
5373 /* Process substitution is not considered to be usual
5374 * 'command execution'.
5375 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5376 */
5377 bb_signals(0
5378 + (1 << SIGTSTP)
5379 + (1 << SIGTTIN)
5380 + (1 << SIGTTOU)
5381 , SIG_IGN);
5382 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5383 close(channel[0]); /* NB: close _first_, then move fd! */
5384 xmove_fd(channel[1], 1);
5385 /* Prevent it from trying to handle ctrl-z etc */
5386 IF_HUSH_JOB(G.run_list_level = 1;)
5387 /* Awful hack for `trap` or $(trap).
5388 *
5389 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5390 * contains an example where "trap" is executed in a subshell:
5391 *
5392 * save_traps=$(trap)
5393 * ...
5394 * eval "$save_traps"
5395 *
5396 * Standard does not say that "trap" in subshell shall print
5397 * parent shell's traps. It only says that its output
5398 * must have suitable form, but then, in the above example
5399 * (which is not supposed to be normative), it implies that.
5400 *
5401 * bash (and probably other shell) does implement it
5402 * (traps are reset to defaults, but "trap" still shows them),
5403 * but as a result, "trap" logic is hopelessly messed up:
5404 *
5405 * # trap
5406 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5407 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5408 * # true | trap <--- trap is in subshell - no output (ditto)
5409 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5410 * trap -- 'echo Ho' SIGWINCH
5411 * # echo `(trap)` <--- in subshell in subshell - output
5412 * trap -- 'echo Ho' SIGWINCH
5413 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5414 * trap -- 'echo Ho' SIGWINCH
5415 *
5416 * The rules when to forget and when to not forget traps
5417 * get really complex and nonsensical.
5418 *
5419 * Our solution: ONLY bare $(trap) or `trap` is special.
5420 */
5421 s = skip_whitespace(s);
5422 if (strncmp(s, "trap", 4) == 0
5423 && skip_whitespace(s + 4)[0] == '\0'
5424 ) {
5425 static const char *const argv[] = { NULL, NULL };
5426 builtin_trap((char**)argv);
5427 exit(0); /* not _exit() - we need to fflush */
5428 }
5429# if BB_MMU
5430 reset_traps_to_defaults();
5431 parse_and_run_string(s);
5432 _exit(G.last_exitcode);
5433# else
5434 /* We re-execute after vfork on NOMMU. This makes this script safe:
5435 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5436 * huge=`cat BIG` # was blocking here forever
5437 * echo OK
5438 */
5439 re_execute_shell(&to_free,
5440 s,
5441 G.global_argv[0],
5442 G.global_argv + 1,
5443 NULL);
5444# endif
5445 }
5446
5447 /* parent */
5448 *pid_p = pid;
5449# if ENABLE_HUSH_FAST
5450 G.count_SIGCHLD++;
5451//bb_error_msg("[%d] fork in generate_stream_from_string:"
5452// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5453// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5454# endif
5455 enable_restore_tty_pgrp_on_exit();
5456# if !BB_MMU
5457 free(to_free);
5458# endif
5459 close(channel[1]);
5460 close_on_exec_on(channel[0]);
5461 return xfdopen_for_read(channel[0]);
5462}
5463
5464/* Return code is exit status of the process that is run. */
5465static int process_command_subs(o_string *dest, const char *s)
5466{
5467 FILE *fp;
5468 struct in_str pipe_str;
5469 pid_t pid;
5470 int status, ch, eol_cnt;
5471
5472 fp = generate_stream_from_string(s, &pid);
5473
5474 /* Now send results of command back into original context */
5475 setup_file_in_str(&pipe_str, fp);
5476 eol_cnt = 0;
5477 while ((ch = i_getch(&pipe_str)) != EOF) {
5478 if (ch == '\n') {
5479 eol_cnt++;
5480 continue;
5481 }
5482 while (eol_cnt) {
5483 o_addchr(dest, '\n');
5484 eol_cnt--;
5485 }
5486 o_addQchr(dest, ch);
5487 }
5488
5489 debug_printf("done reading from `cmd` pipe, closing it\n");
5490 fclose(fp);
5491 /* We need to extract exitcode. Test case
5492 * "true; echo `sleep 1; false` $?"
5493 * should print 1 */
5494 safe_waitpid(pid, &status, 0);
5495 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5496 return WEXITSTATUS(status);
5497}
5498#endif /* ENABLE_HUSH_TICK */
5499
5500
5501static void setup_heredoc(struct redir_struct *redir)
5502{
5503 struct fd_pair pair;
5504 pid_t pid;
5505 int len, written;
5506 /* the _body_ of heredoc (misleading field name) */
5507 const char *heredoc = redir->rd_filename;
5508 char *expanded;
5509#if !BB_MMU
5510 char **to_free;
5511#endif
5512
5513 expanded = NULL;
5514 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005515 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005516 if (expanded)
5517 heredoc = expanded;
5518 }
5519 len = strlen(heredoc);
5520
5521 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5522 xpiped_pair(pair);
5523 xmove_fd(pair.rd, redir->rd_fd);
5524
5525 /* Try writing without forking. Newer kernels have
5526 * dynamically growing pipes. Must use non-blocking write! */
5527 ndelay_on(pair.wr);
5528 while (1) {
5529 written = write(pair.wr, heredoc, len);
5530 if (written <= 0)
5531 break;
5532 len -= written;
5533 if (len == 0) {
5534 close(pair.wr);
5535 free(expanded);
5536 return;
5537 }
5538 heredoc += written;
5539 }
5540 ndelay_off(pair.wr);
5541
5542 /* Okay, pipe buffer was not big enough */
5543 /* Note: we must not create a stray child (bastard? :)
5544 * for the unsuspecting parent process. Child creates a grandchild
5545 * and exits before parent execs the process which consumes heredoc
5546 * (that exec happens after we return from this function) */
5547#if !BB_MMU
5548 to_free = NULL;
5549#endif
5550 pid = xvfork();
5551 if (pid == 0) {
5552 /* child */
5553 disable_restore_tty_pgrp_on_exit();
5554 pid = BB_MMU ? xfork() : xvfork();
5555 if (pid != 0)
5556 _exit(0);
5557 /* grandchild */
5558 close(redir->rd_fd); /* read side of the pipe */
5559#if BB_MMU
5560 full_write(pair.wr, heredoc, len); /* may loop or block */
5561 _exit(0);
5562#else
5563 /* Delegate blocking writes to another process */
5564 xmove_fd(pair.wr, STDOUT_FILENO);
5565 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5566#endif
5567 }
5568 /* parent */
5569#if ENABLE_HUSH_FAST
5570 G.count_SIGCHLD++;
5571//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5572#endif
5573 enable_restore_tty_pgrp_on_exit();
5574#if !BB_MMU
5575 free(to_free);
5576#endif
5577 close(pair.wr);
5578 free(expanded);
5579 wait(NULL); /* wait till child has died */
5580}
5581
5582/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5583 * and stderr if they are redirected. */
5584static int setup_redirects(struct command *prog, int squirrel[])
5585{
5586 int openfd, mode;
5587 struct redir_struct *redir;
5588
5589 for (redir = prog->redirects; redir; redir = redir->next) {
5590 if (redir->rd_type == REDIRECT_HEREDOC2) {
5591 /* rd_fd<<HERE case */
5592 if (squirrel && redir->rd_fd < 3
5593 && squirrel[redir->rd_fd] < 0
5594 ) {
5595 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5596 }
5597 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5598 * of the heredoc */
5599 debug_printf_parse("set heredoc '%s'\n",
5600 redir->rd_filename);
5601 setup_heredoc(redir);
5602 continue;
5603 }
5604
5605 if (redir->rd_dup == REDIRFD_TO_FILE) {
5606 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5607 char *p;
5608 if (redir->rd_filename == NULL) {
5609 /* Something went wrong in the parse.
5610 * Pretend it didn't happen */
5611 bb_error_msg("bug in redirect parse");
5612 continue;
5613 }
5614 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005615 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005616 openfd = open_or_warn(p, mode);
5617 free(p);
5618 if (openfd < 0) {
5619 /* this could get lost if stderr has been redirected, but
5620 * bash and ash both lose it as well (though zsh doesn't!) */
5621//what the above comment tries to say?
5622 return 1;
5623 }
5624 } else {
5625 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5626 openfd = redir->rd_dup;
5627 }
5628
5629 if (openfd != redir->rd_fd) {
5630 if (squirrel && redir->rd_fd < 3
5631 && squirrel[redir->rd_fd] < 0
5632 ) {
5633 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5634 }
5635 if (openfd == REDIRFD_CLOSE) {
5636 /* "n>-" means "close me" */
5637 close(redir->rd_fd);
5638 } else {
5639 xdup2(openfd, redir->rd_fd);
5640 if (redir->rd_dup == REDIRFD_TO_FILE)
5641 close(openfd);
5642 }
5643 }
5644 }
5645 return 0;
5646}
5647
5648static void restore_redirects(int squirrel[])
5649{
5650 int i, fd;
5651 for (i = 0; i < 3; i++) {
5652 fd = squirrel[i];
5653 if (fd != -1) {
5654 /* We simply die on error */
5655 xmove_fd(fd, i);
5656 }
5657 }
5658}
5659
5660static char *find_in_path(const char *arg)
5661{
5662 char *ret = NULL;
5663 const char *PATH = get_local_var_value("PATH");
5664
5665 if (!PATH)
5666 return NULL;
5667
5668 while (1) {
5669 const char *end = strchrnul(PATH, ':');
5670 int sz = end - PATH; /* must be int! */
5671
5672 free(ret);
5673 if (sz != 0) {
5674 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5675 } else {
5676 /* We have xxx::yyyy in $PATH,
5677 * it means "use current dir" */
5678 ret = xstrdup(arg);
5679 }
5680 if (access(ret, F_OK) == 0)
5681 break;
5682
5683 if (*end == '\0') {
5684 free(ret);
5685 return NULL;
5686 }
5687 PATH = end + 1;
5688 }
5689
5690 return ret;
5691}
5692
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005693static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005694 const struct built_in_command *x,
5695 const struct built_in_command *end)
5696{
5697 while (x != end) {
5698 if (strcmp(name, x->b_cmd) != 0) {
5699 x++;
5700 continue;
5701 }
5702 debug_printf_exec("found builtin '%s'\n", name);
5703 return x;
5704 }
5705 return NULL;
5706}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005707static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005708{
5709 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5710}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005711static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005712{
5713 const struct built_in_command *x = find_builtin1(name);
5714 if (x)
5715 return x;
5716 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5717}
5718
5719#if ENABLE_HUSH_FUNCTIONS
5720static struct function **find_function_slot(const char *name)
5721{
5722 struct function **funcpp = &G.top_func;
5723 while (*funcpp) {
5724 if (strcmp(name, (*funcpp)->name) == 0) {
5725 break;
5726 }
5727 funcpp = &(*funcpp)->next;
5728 }
5729 return funcpp;
5730}
5731
5732static const struct function *find_function(const char *name)
5733{
5734 const struct function *funcp = *find_function_slot(name);
5735 if (funcp)
5736 debug_printf_exec("found function '%s'\n", name);
5737 return funcp;
5738}
5739
5740/* Note: takes ownership on name ptr */
5741static struct function *new_function(char *name)
5742{
5743 struct function **funcpp = find_function_slot(name);
5744 struct function *funcp = *funcpp;
5745
5746 if (funcp != NULL) {
5747 struct command *cmd = funcp->parent_cmd;
5748 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5749 if (!cmd) {
5750 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5751 free(funcp->name);
5752 /* Note: if !funcp->body, do not free body_as_string!
5753 * This is a special case of "-F name body" function:
5754 * body_as_string was not malloced! */
5755 if (funcp->body) {
5756 free_pipe_list(funcp->body);
5757# if !BB_MMU
5758 free(funcp->body_as_string);
5759# endif
5760 }
5761 } else {
5762 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5763 cmd->argv[0] = funcp->name;
5764 cmd->group = funcp->body;
5765# if !BB_MMU
5766 cmd->group_as_string = funcp->body_as_string;
5767# endif
5768 }
5769 } else {
5770 debug_printf_exec("remembering new function '%s'\n", name);
5771 funcp = *funcpp = xzalloc(sizeof(*funcp));
5772 /*funcp->next = NULL;*/
5773 }
5774
5775 funcp->name = name;
5776 return funcp;
5777}
5778
5779static void unset_func(const char *name)
5780{
5781 struct function **funcpp = find_function_slot(name);
5782 struct function *funcp = *funcpp;
5783
5784 if (funcp != NULL) {
5785 debug_printf_exec("freeing function '%s'\n", funcp->name);
5786 *funcpp = funcp->next;
5787 /* funcp is unlinked now, deleting it.
5788 * Note: if !funcp->body, the function was created by
5789 * "-F name body", do not free ->body_as_string
5790 * and ->name as they were not malloced. */
5791 if (funcp->body) {
5792 free_pipe_list(funcp->body);
5793 free(funcp->name);
5794# if !BB_MMU
5795 free(funcp->body_as_string);
5796# endif
5797 }
5798 free(funcp);
5799 }
5800}
5801
5802# if BB_MMU
5803#define exec_function(to_free, funcp, argv) \
5804 exec_function(funcp, argv)
5805# endif
5806static void exec_function(char ***to_free,
5807 const struct function *funcp,
5808 char **argv) NORETURN;
5809static void exec_function(char ***to_free,
5810 const struct function *funcp,
5811 char **argv)
5812{
5813# if BB_MMU
5814 int n = 1;
5815
5816 argv[0] = G.global_argv[0];
5817 G.global_argv = argv;
5818 while (*++argv)
5819 n++;
5820 G.global_argc = n;
5821 /* On MMU, funcp->body is always non-NULL */
5822 n = run_list(funcp->body);
5823 fflush_all();
5824 _exit(n);
5825# else
5826 re_execute_shell(to_free,
5827 funcp->body_as_string,
5828 G.global_argv[0],
5829 argv + 1,
5830 NULL);
5831# endif
5832}
5833
5834static int run_function(const struct function *funcp, char **argv)
5835{
5836 int rc;
5837 save_arg_t sv;
5838 smallint sv_flg;
5839
5840 save_and_replace_G_args(&sv, argv);
5841
5842 /* "we are in function, ok to use return" */
5843 sv_flg = G.flag_return_in_progress;
5844 G.flag_return_in_progress = -1;
5845# if ENABLE_HUSH_LOCAL
5846 G.func_nest_level++;
5847# endif
5848
5849 /* On MMU, funcp->body is always non-NULL */
5850# if !BB_MMU
5851 if (!funcp->body) {
5852 /* Function defined by -F */
5853 parse_and_run_string(funcp->body_as_string);
5854 rc = G.last_exitcode;
5855 } else
5856# endif
5857 {
5858 rc = run_list(funcp->body);
5859 }
5860
5861# if ENABLE_HUSH_LOCAL
5862 {
5863 struct variable *var;
5864 struct variable **var_pp;
5865
5866 var_pp = &G.top_var;
5867 while ((var = *var_pp) != NULL) {
5868 if (var->func_nest_level < G.func_nest_level) {
5869 var_pp = &var->next;
5870 continue;
5871 }
5872 /* Unexport */
5873 if (var->flg_export)
5874 bb_unsetenv(var->varstr);
5875 /* Remove from global list */
5876 *var_pp = var->next;
5877 /* Free */
5878 if (!var->max_len)
5879 free(var->varstr);
5880 free(var);
5881 }
5882 G.func_nest_level--;
5883 }
5884# endif
5885 G.flag_return_in_progress = sv_flg;
5886
5887 restore_G_args(&sv, argv);
5888
5889 return rc;
5890}
5891#endif /* ENABLE_HUSH_FUNCTIONS */
5892
5893
5894#if BB_MMU
5895#define exec_builtin(to_free, x, argv) \
5896 exec_builtin(x, argv)
5897#else
5898#define exec_builtin(to_free, x, argv) \
5899 exec_builtin(to_free, argv)
5900#endif
5901static void exec_builtin(char ***to_free,
5902 const struct built_in_command *x,
5903 char **argv) NORETURN;
5904static void exec_builtin(char ***to_free,
5905 const struct built_in_command *x,
5906 char **argv)
5907{
5908#if BB_MMU
5909 int rcode = x->b_function(argv);
5910 fflush_all();
5911 _exit(rcode);
5912#else
5913 /* On NOMMU, we must never block!
5914 * Example: { sleep 99 | read line; } & echo Ok
5915 */
5916 re_execute_shell(to_free,
5917 argv[0],
5918 G.global_argv[0],
5919 G.global_argv + 1,
5920 argv);
5921#endif
5922}
5923
5924
5925static void execvp_or_die(char **argv) NORETURN;
5926static void execvp_or_die(char **argv)
5927{
5928 debug_printf_exec("execing '%s'\n", argv[0]);
5929 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5930 execvp(argv[0], argv);
5931 bb_perror_msg("can't execute '%s'", argv[0]);
5932 _exit(127); /* bash compat */
5933}
5934
5935#if ENABLE_HUSH_MODE_X
5936static void dump_cmd_in_x_mode(char **argv)
5937{
5938 if (G_x_mode && argv) {
5939 /* We want to output the line in one write op */
5940 char *buf, *p;
5941 int len;
5942 int n;
5943
5944 len = 3;
5945 n = 0;
5946 while (argv[n])
5947 len += strlen(argv[n++]) + 1;
5948 buf = xmalloc(len);
5949 buf[0] = '+';
5950 p = buf + 1;
5951 n = 0;
5952 while (argv[n])
5953 p += sprintf(p, " %s", argv[n++]);
5954 *p++ = '\n';
5955 *p = '\0';
5956 fputs(buf, stderr);
5957 free(buf);
5958 }
5959}
5960#else
5961# define dump_cmd_in_x_mode(argv) ((void)0)
5962#endif
5963
5964#if BB_MMU
5965#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5966 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5967#define pseudo_exec(nommu_save, command, argv_expanded) \
5968 pseudo_exec(command, argv_expanded)
5969#endif
5970
5971/* Called after [v]fork() in run_pipe, or from builtin_exec.
5972 * Never returns.
5973 * Don't exit() here. If you don't exec, use _exit instead.
5974 * The at_exit handlers apparently confuse the calling process,
5975 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5976static void pseudo_exec_argv(nommu_save_t *nommu_save,
5977 char **argv, int assignment_cnt,
5978 char **argv_expanded) NORETURN;
5979static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5980 char **argv, int assignment_cnt,
5981 char **argv_expanded)
5982{
5983 char **new_env;
5984
5985 new_env = expand_assignments(argv, assignment_cnt);
5986 dump_cmd_in_x_mode(new_env);
5987
5988 if (!argv[assignment_cnt]) {
5989 /* Case when we are here: ... | var=val | ...
5990 * (note that we do not exit early, i.e., do not optimize out
5991 * expand_assignments(): think about ... | var=`sleep 1` | ...
5992 */
5993 free_strings(new_env);
5994 _exit(EXIT_SUCCESS);
5995 }
5996
5997#if BB_MMU
5998 set_vars_and_save_old(new_env);
5999 free(new_env); /* optional */
6000 /* we can also destroy set_vars_and_save_old's return value,
6001 * to save memory */
6002#else
6003 nommu_save->new_env = new_env;
6004 nommu_save->old_vars = set_vars_and_save_old(new_env);
6005#endif
6006
6007 if (argv_expanded) {
6008 argv = argv_expanded;
6009 } else {
6010 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6011#if !BB_MMU
6012 nommu_save->argv = argv;
6013#endif
6014 }
6015 dump_cmd_in_x_mode(argv);
6016
6017#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6018 if (strchr(argv[0], '/') != NULL)
6019 goto skip;
6020#endif
6021
6022 /* Check if the command matches any of the builtins.
6023 * Depending on context, this might be redundant. But it's
6024 * easier to waste a few CPU cycles than it is to figure out
6025 * if this is one of those cases.
6026 */
6027 {
6028 /* On NOMMU, it is more expensive to re-execute shell
6029 * just in order to run echo or test builtin.
6030 * It's better to skip it here and run corresponding
6031 * non-builtin later. */
6032 const struct built_in_command *x;
6033 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6034 if (x) {
6035 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6036 }
6037 }
6038#if ENABLE_HUSH_FUNCTIONS
6039 /* Check if the command matches any functions */
6040 {
6041 const struct function *funcp = find_function(argv[0]);
6042 if (funcp) {
6043 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6044 }
6045 }
6046#endif
6047
6048#if ENABLE_FEATURE_SH_STANDALONE
6049 /* Check if the command matches any busybox applets */
6050 {
6051 int a = find_applet_by_name(argv[0]);
6052 if (a >= 0) {
6053# if BB_MMU /* see above why on NOMMU it is not allowed */
6054 if (APPLET_IS_NOEXEC(a)) {
6055 debug_printf_exec("running applet '%s'\n", argv[0]);
6056 run_applet_no_and_exit(a, argv);
6057 }
6058# endif
6059 /* Re-exec ourselves */
6060 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6061 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6062 execv(bb_busybox_exec_path, argv);
6063 /* If they called chroot or otherwise made the binary no longer
6064 * executable, fall through */
6065 }
6066 }
6067#endif
6068
6069#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6070 skip:
6071#endif
6072 execvp_or_die(argv);
6073}
6074
6075/* Called after [v]fork() in run_pipe
6076 */
6077static void pseudo_exec(nommu_save_t *nommu_save,
6078 struct command *command,
6079 char **argv_expanded) NORETURN;
6080static void pseudo_exec(nommu_save_t *nommu_save,
6081 struct command *command,
6082 char **argv_expanded)
6083{
6084 if (command->argv) {
6085 pseudo_exec_argv(nommu_save, command->argv,
6086 command->assignment_cnt, argv_expanded);
6087 }
6088
6089 if (command->group) {
6090 /* Cases when we are here:
6091 * ( list )
6092 * { list } &
6093 * ... | ( list ) | ...
6094 * ... | { list } | ...
6095 */
6096#if BB_MMU
6097 int rcode;
6098 debug_printf_exec("pseudo_exec: run_list\n");
6099 reset_traps_to_defaults();
6100 rcode = run_list(command->group);
6101 /* OK to leak memory by not calling free_pipe_list,
6102 * since this process is about to exit */
6103 _exit(rcode);
6104#else
6105 re_execute_shell(&nommu_save->argv_from_re_execing,
6106 command->group_as_string,
6107 G.global_argv[0],
6108 G.global_argv + 1,
6109 NULL);
6110#endif
6111 }
6112
6113 /* Case when we are here: ... | >file */
6114 debug_printf_exec("pseudo_exec'ed null command\n");
6115 _exit(EXIT_SUCCESS);
6116}
6117
6118#if ENABLE_HUSH_JOB
6119static const char *get_cmdtext(struct pipe *pi)
6120{
6121 char **argv;
6122 char *p;
6123 int len;
6124
6125 /* This is subtle. ->cmdtext is created only on first backgrounding.
6126 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6127 * On subsequent bg argv is trashed, but we won't use it */
6128 if (pi->cmdtext)
6129 return pi->cmdtext;
6130 argv = pi->cmds[0].argv;
6131 if (!argv || !argv[0]) {
6132 pi->cmdtext = xzalloc(1);
6133 return pi->cmdtext;
6134 }
6135
6136 len = 0;
6137 do {
6138 len += strlen(*argv) + 1;
6139 } while (*++argv);
6140 p = xmalloc(len);
6141 pi->cmdtext = p;
6142 argv = pi->cmds[0].argv;
6143 do {
6144 len = strlen(*argv);
6145 memcpy(p, *argv, len);
6146 p += len;
6147 *p++ = ' ';
6148 } while (*++argv);
6149 p[-1] = '\0';
6150 return pi->cmdtext;
6151}
6152
6153static void insert_bg_job(struct pipe *pi)
6154{
6155 struct pipe *job, **jobp;
6156 int i;
6157
6158 /* Linear search for the ID of the job to use */
6159 pi->jobid = 1;
6160 for (job = G.job_list; job; job = job->next)
6161 if (job->jobid >= pi->jobid)
6162 pi->jobid = job->jobid + 1;
6163
6164 /* Add job to the list of running jobs */
6165 jobp = &G.job_list;
6166 while ((job = *jobp) != NULL)
6167 jobp = &job->next;
6168 job = *jobp = xmalloc(sizeof(*job));
6169
6170 *job = *pi; /* physical copy */
6171 job->next = NULL;
6172 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6173 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6174 for (i = 0; i < pi->num_cmds; i++) {
6175 job->cmds[i].pid = pi->cmds[i].pid;
6176 /* all other fields are not used and stay zero */
6177 }
6178 job->cmdtext = xstrdup(get_cmdtext(pi));
6179
6180 if (G_interactive_fd)
6181 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6182 G.last_jobid = job->jobid;
6183}
6184
6185static void remove_bg_job(struct pipe *pi)
6186{
6187 struct pipe *prev_pipe;
6188
6189 if (pi == G.job_list) {
6190 G.job_list = pi->next;
6191 } else {
6192 prev_pipe = G.job_list;
6193 while (prev_pipe->next != pi)
6194 prev_pipe = prev_pipe->next;
6195 prev_pipe->next = pi->next;
6196 }
6197 if (G.job_list)
6198 G.last_jobid = G.job_list->jobid;
6199 else
6200 G.last_jobid = 0;
6201}
6202
6203/* Remove a backgrounded job */
6204static void delete_finished_bg_job(struct pipe *pi)
6205{
6206 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006207 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006208}
6209#endif /* JOB */
6210
6211/* Check to see if any processes have exited -- if they
6212 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006213static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006214{
6215 int attributes;
6216 int status;
6217#if ENABLE_HUSH_JOB
6218 struct pipe *pi;
6219#endif
6220 pid_t childpid;
6221 int rcode = 0;
6222
6223 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6224
6225 attributes = WUNTRACED;
6226 if (fg_pipe == NULL)
6227 attributes |= WNOHANG;
6228
6229 errno = 0;
6230#if ENABLE_HUSH_FAST
6231 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6232//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6233//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6234 /* There was neither fork nor SIGCHLD since last waitpid */
6235 /* Avoid doing waitpid syscall if possible */
6236 if (!G.we_have_children) {
6237 errno = ECHILD;
6238 return -1;
6239 }
6240 if (fg_pipe == NULL) { /* is WNOHANG set? */
6241 /* We have children, but they did not exit
6242 * or stop yet (we saw no SIGCHLD) */
6243 return 0;
6244 }
6245 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6246 }
6247#endif
6248
6249/* Do we do this right?
6250 * bash-3.00# sleep 20 | false
6251 * <ctrl-Z pressed>
6252 * [3]+ Stopped sleep 20 | false
6253 * bash-3.00# echo $?
6254 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6255 * [hush 1.14.0: yes we do it right]
6256 */
6257 wait_more:
6258 while (1) {
6259 int i;
6260 int dead;
6261
6262#if ENABLE_HUSH_FAST
6263 i = G.count_SIGCHLD;
6264#endif
6265 childpid = waitpid(-1, &status, attributes);
6266 if (childpid <= 0) {
6267 if (childpid && errno != ECHILD)
6268 bb_perror_msg("waitpid");
6269#if ENABLE_HUSH_FAST
6270 else { /* Until next SIGCHLD, waitpid's are useless */
6271 G.we_have_children = (childpid == 0);
6272 G.handled_SIGCHLD = i;
6273//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6274 }
6275#endif
6276 break;
6277 }
6278 dead = WIFEXITED(status) || WIFSIGNALED(status);
6279
6280#if DEBUG_JOBS
6281 if (WIFSTOPPED(status))
6282 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6283 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6284 if (WIFSIGNALED(status))
6285 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6286 childpid, WTERMSIG(status), WEXITSTATUS(status));
6287 if (WIFEXITED(status))
6288 debug_printf_jobs("pid %d exited, exitcode %d\n",
6289 childpid, WEXITSTATUS(status));
6290#endif
6291 /* Were we asked to wait for fg pipe? */
6292 if (fg_pipe) {
6293 for (i = 0; i < fg_pipe->num_cmds; i++) {
6294 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6295 if (fg_pipe->cmds[i].pid != childpid)
6296 continue;
6297 if (dead) {
6298 fg_pipe->cmds[i].pid = 0;
6299 fg_pipe->alive_cmds--;
6300 if (i == fg_pipe->num_cmds - 1) {
6301 /* last process gives overall exitstatus */
6302 rcode = WEXITSTATUS(status);
6303 /* bash prints killer signal's name for *last*
6304 * process in pipe (prints just newline for SIGINT).
6305 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6306 */
6307 if (WIFSIGNALED(status)) {
6308 int sig = WTERMSIG(status);
6309 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6310 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6311 * Maybe we need to use sig | 128? */
6312 rcode = sig + 128;
6313 }
6314 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6315 }
6316 } else {
6317 fg_pipe->cmds[i].is_stopped = 1;
6318 fg_pipe->stopped_cmds++;
6319 }
6320 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6321 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6322 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6323 /* All processes in fg pipe have exited or stopped */
6324/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6325 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6326 * and "killall -STOP cat" */
6327 if (G_interactive_fd) {
6328#if ENABLE_HUSH_JOB
6329 if (fg_pipe->alive_cmds)
6330 insert_bg_job(fg_pipe);
6331#endif
6332 return rcode;
6333 }
6334 if (!fg_pipe->alive_cmds)
6335 return rcode;
6336 }
6337 /* There are still running processes in the fg pipe */
6338 goto wait_more; /* do waitpid again */
6339 }
6340 /* it wasnt fg_pipe, look for process in bg pipes */
6341 }
6342
6343#if ENABLE_HUSH_JOB
6344 /* We asked to wait for bg or orphaned children */
6345 /* No need to remember exitcode in this case */
6346 for (pi = G.job_list; pi; pi = pi->next) {
6347 for (i = 0; i < pi->num_cmds; i++) {
6348 if (pi->cmds[i].pid == childpid)
6349 goto found_pi_and_prognum;
6350 }
6351 }
6352 /* Happens when shell is used as init process (init=/bin/sh) */
6353 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6354 continue; /* do waitpid again */
6355
6356 found_pi_and_prognum:
6357 if (dead) {
6358 /* child exited */
6359 pi->cmds[i].pid = 0;
6360 pi->alive_cmds--;
6361 if (!pi->alive_cmds) {
6362 if (G_interactive_fd)
6363 printf(JOB_STATUS_FORMAT, pi->jobid,
6364 "Done", pi->cmdtext);
6365 delete_finished_bg_job(pi);
6366 }
6367 } else {
6368 /* child stopped */
6369 pi->cmds[i].is_stopped = 1;
6370 pi->stopped_cmds++;
6371 }
6372#endif
6373 } /* while (waitpid succeeds)... */
6374
6375 return rcode;
6376}
6377
6378#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006379static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006380{
6381 pid_t p;
6382 int rcode = checkjobs(fg_pipe);
6383 if (G_saved_tty_pgrp) {
6384 /* Job finished, move the shell to the foreground */
6385 p = getpgrp(); /* our process group id */
6386 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6387 tcsetpgrp(G_interactive_fd, p);
6388 }
6389 return rcode;
6390}
6391#endif
6392
6393/* Start all the jobs, but don't wait for anything to finish.
6394 * See checkjobs().
6395 *
6396 * Return code is normally -1, when the caller has to wait for children
6397 * to finish to determine the exit status of the pipe. If the pipe
6398 * is a simple builtin command, however, the action is done by the
6399 * time run_pipe returns, and the exit code is provided as the
6400 * return value.
6401 *
6402 * Returns -1 only if started some children. IOW: we have to
6403 * mask out retvals of builtins etc with 0xff!
6404 *
6405 * The only case when we do not need to [v]fork is when the pipe
6406 * is single, non-backgrounded, non-subshell command. Examples:
6407 * cmd ; ... { list } ; ...
6408 * cmd && ... { list } && ...
6409 * cmd || ... { list } || ...
6410 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6411 * or (if SH_STANDALONE) an applet, and we can run the { list }
6412 * with run_list. If it isn't one of these, we fork and exec cmd.
6413 *
6414 * Cases when we must fork:
6415 * non-single: cmd | cmd
6416 * backgrounded: cmd & { list } &
6417 * subshell: ( list ) [&]
6418 */
6419#if !ENABLE_HUSH_MODE_X
6420#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6421 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6422#endif
6423static int redirect_and_varexp_helper(char ***new_env_p,
6424 struct variable **old_vars_p,
6425 struct command *command,
6426 int squirrel[3],
6427 char **argv_expanded)
6428{
6429 /* setup_redirects acts on file descriptors, not FILEs.
6430 * This is perfect for work that comes after exec().
6431 * Is it really safe for inline use? Experimentally,
6432 * things seem to work. */
6433 int rcode = setup_redirects(command, squirrel);
6434 if (rcode == 0) {
6435 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6436 *new_env_p = new_env;
6437 dump_cmd_in_x_mode(new_env);
6438 dump_cmd_in_x_mode(argv_expanded);
6439 if (old_vars_p)
6440 *old_vars_p = set_vars_and_save_old(new_env);
6441 }
6442 return rcode;
6443}
6444static NOINLINE int run_pipe(struct pipe *pi)
6445{
6446 static const char *const null_ptr = NULL;
6447
6448 int cmd_no;
6449 int next_infd;
6450 struct command *command;
6451 char **argv_expanded;
6452 char **argv;
6453 /* it is not always needed, but we aim to smaller code */
6454 int squirrel[] = { -1, -1, -1 };
6455 int rcode;
6456
6457 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6458 debug_enter();
6459
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006460 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6461 * Result should be 3 lines: q w e, qwe, q w e
6462 */
6463 G.ifs = get_local_var_value("IFS");
6464 if (!G.ifs)
6465 G.ifs = defifs;
6466
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006467 IF_HUSH_JOB(pi->pgrp = -1;)
6468 pi->stopped_cmds = 0;
6469 command = &pi->cmds[0];
6470 argv_expanded = NULL;
6471
6472 if (pi->num_cmds != 1
6473 || pi->followup == PIPE_BG
6474 || command->cmd_type == CMD_SUBSHELL
6475 ) {
6476 goto must_fork;
6477 }
6478
6479 pi->alive_cmds = 1;
6480
6481 debug_printf_exec(": group:%p argv:'%s'\n",
6482 command->group, command->argv ? command->argv[0] : "NONE");
6483
6484 if (command->group) {
6485#if ENABLE_HUSH_FUNCTIONS
6486 if (command->cmd_type == CMD_FUNCDEF) {
6487 /* "executing" func () { list } */
6488 struct function *funcp;
6489
6490 funcp = new_function(command->argv[0]);
6491 /* funcp->name is already set to argv[0] */
6492 funcp->body = command->group;
6493# if !BB_MMU
6494 funcp->body_as_string = command->group_as_string;
6495 command->group_as_string = NULL;
6496# endif
6497 command->group = NULL;
6498 command->argv[0] = NULL;
6499 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6500 funcp->parent_cmd = command;
6501 command->child_func = funcp;
6502
6503 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6504 debug_leave();
6505 return EXIT_SUCCESS;
6506 }
6507#endif
6508 /* { list } */
6509 debug_printf("non-subshell group\n");
6510 rcode = 1; /* exitcode if redir failed */
6511 if (setup_redirects(command, squirrel) == 0) {
6512 debug_printf_exec(": run_list\n");
6513 rcode = run_list(command->group) & 0xff;
6514 }
6515 restore_redirects(squirrel);
6516 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6517 debug_leave();
6518 debug_printf_exec("run_pipe: return %d\n", rcode);
6519 return rcode;
6520 }
6521
6522 argv = command->argv ? command->argv : (char **) &null_ptr;
6523 {
6524 const struct built_in_command *x;
6525#if ENABLE_HUSH_FUNCTIONS
6526 const struct function *funcp;
6527#else
6528 enum { funcp = 0 };
6529#endif
6530 char **new_env = NULL;
6531 struct variable *old_vars = NULL;
6532
6533 if (argv[command->assignment_cnt] == NULL) {
6534 /* Assignments, but no command */
6535 /* Ensure redirects take effect (that is, create files).
6536 * Try "a=t >file" */
6537#if 0 /* A few cases in testsuite fail with this code. FIXME */
6538 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6539 /* Set shell variables */
6540 if (new_env) {
6541 argv = new_env;
6542 while (*argv) {
6543 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6544 /* Do we need to flag set_local_var() errors?
6545 * "assignment to readonly var" and "putenv error"
6546 */
6547 argv++;
6548 }
6549 }
6550 /* Redirect error sets $? to 1. Otherwise,
6551 * if evaluating assignment value set $?, retain it.
6552 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6553 if (rcode == 0)
6554 rcode = G.last_exitcode;
6555 /* Exit, _skipping_ variable restoring code: */
6556 goto clean_up_and_ret0;
6557
6558#else /* Older, bigger, but more correct code */
6559
6560 rcode = setup_redirects(command, squirrel);
6561 restore_redirects(squirrel);
6562 /* Set shell variables */
6563 if (G_x_mode)
6564 bb_putchar_stderr('+');
6565 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006566 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006567 if (G_x_mode)
6568 fprintf(stderr, " %s", p);
6569 debug_printf_exec("set shell var:'%s'->'%s'\n",
6570 *argv, p);
6571 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6572 /* Do we need to flag set_local_var() errors?
6573 * "assignment to readonly var" and "putenv error"
6574 */
6575 argv++;
6576 }
6577 if (G_x_mode)
6578 bb_putchar_stderr('\n');
6579 /* Redirect error sets $? to 1. Otherwise,
6580 * if evaluating assignment value set $?, retain it.
6581 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6582 if (rcode == 0)
6583 rcode = G.last_exitcode;
6584 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6585 debug_leave();
6586 debug_printf_exec("run_pipe: return %d\n", rcode);
6587 return rcode;
6588#endif
6589 }
6590
6591 /* Expand the rest into (possibly) many strings each */
6592 if (0) {}
6593#if ENABLE_HUSH_BASH_COMPAT
6594 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6595 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6596 }
6597#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006598 else {
6599 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6600 }
6601
6602 /* if someone gives us an empty string: `cmd with empty output` */
6603 if (!argv_expanded[0]) {
6604 free(argv_expanded);
6605 debug_leave();
6606 return G.last_exitcode;
6607 }
6608
6609 x = find_builtin(argv_expanded[0]);
6610#if ENABLE_HUSH_FUNCTIONS
6611 funcp = NULL;
6612 if (!x)
6613 funcp = find_function(argv_expanded[0]);
6614#endif
6615 if (x || funcp) {
6616 if (!funcp) {
6617 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6618 debug_printf("exec with redirects only\n");
6619 rcode = setup_redirects(command, NULL);
6620 goto clean_up_and_ret1;
6621 }
6622 }
6623 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6624 if (rcode == 0) {
6625 if (!funcp) {
6626 debug_printf_exec(": builtin '%s' '%s'...\n",
6627 x->b_cmd, argv_expanded[1]);
6628 rcode = x->b_function(argv_expanded) & 0xff;
6629 fflush_all();
6630 }
6631#if ENABLE_HUSH_FUNCTIONS
6632 else {
6633# if ENABLE_HUSH_LOCAL
6634 struct variable **sv;
6635 sv = G.shadowed_vars_pp;
6636 G.shadowed_vars_pp = &old_vars;
6637# endif
6638 debug_printf_exec(": function '%s' '%s'...\n",
6639 funcp->name, argv_expanded[1]);
6640 rcode = run_function(funcp, argv_expanded) & 0xff;
6641# if ENABLE_HUSH_LOCAL
6642 G.shadowed_vars_pp = sv;
6643# endif
6644 }
6645#endif
6646 }
6647 clean_up_and_ret:
6648 unset_vars(new_env);
6649 add_vars(old_vars);
6650/* clean_up_and_ret0: */
6651 restore_redirects(squirrel);
6652 clean_up_and_ret1:
6653 free(argv_expanded);
6654 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6655 debug_leave();
6656 debug_printf_exec("run_pipe return %d\n", rcode);
6657 return rcode;
6658 }
6659
6660 if (ENABLE_FEATURE_SH_STANDALONE) {
6661 int n = find_applet_by_name(argv_expanded[0]);
6662 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6663 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6664 if (rcode == 0) {
6665 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6666 argv_expanded[0], argv_expanded[1]);
6667 rcode = run_nofork_applet(n, argv_expanded);
6668 }
6669 goto clean_up_and_ret;
6670 }
6671 }
6672 /* It is neither builtin nor applet. We must fork. */
6673 }
6674
6675 must_fork:
6676 /* NB: argv_expanded may already be created, and that
6677 * might include `cmd` runs! Do not rerun it! We *must*
6678 * use argv_expanded if it's non-NULL */
6679
6680 /* Going to fork a child per each pipe member */
6681 pi->alive_cmds = 0;
6682 next_infd = 0;
6683
6684 cmd_no = 0;
6685 while (cmd_no < pi->num_cmds) {
6686 struct fd_pair pipefds;
6687#if !BB_MMU
6688 volatile nommu_save_t nommu_save;
6689 nommu_save.new_env = NULL;
6690 nommu_save.old_vars = NULL;
6691 nommu_save.argv = NULL;
6692 nommu_save.argv_from_re_execing = NULL;
6693#endif
6694 command = &pi->cmds[cmd_no];
6695 cmd_no++;
6696 if (command->argv) {
6697 debug_printf_exec(": pipe member '%s' '%s'...\n",
6698 command->argv[0], command->argv[1]);
6699 } else {
6700 debug_printf_exec(": pipe member with no argv\n");
6701 }
6702
6703 /* pipes are inserted between pairs of commands */
6704 pipefds.rd = 0;
6705 pipefds.wr = 1;
6706 if (cmd_no < pi->num_cmds)
6707 xpiped_pair(pipefds);
6708
6709 command->pid = BB_MMU ? fork() : vfork();
6710 if (!command->pid) { /* child */
6711#if ENABLE_HUSH_JOB
6712 disable_restore_tty_pgrp_on_exit();
6713 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6714
6715 /* Every child adds itself to new process group
6716 * with pgid == pid_of_first_child_in_pipe */
6717 if (G.run_list_level == 1 && G_interactive_fd) {
6718 pid_t pgrp;
6719 pgrp = pi->pgrp;
6720 if (pgrp < 0) /* true for 1st process only */
6721 pgrp = getpid();
6722 if (setpgid(0, pgrp) == 0
6723 && pi->followup != PIPE_BG
6724 && G_saved_tty_pgrp /* we have ctty */
6725 ) {
6726 /* We do it in *every* child, not just first,
6727 * to avoid races */
6728 tcsetpgrp(G_interactive_fd, pgrp);
6729 }
6730 }
6731#endif
6732 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6733 /* 1st cmd in backgrounded pipe
6734 * should have its stdin /dev/null'ed */
6735 close(0);
6736 if (open(bb_dev_null, O_RDONLY))
6737 xopen("/", O_RDONLY);
6738 } else {
6739 xmove_fd(next_infd, 0);
6740 }
6741 xmove_fd(pipefds.wr, 1);
6742 if (pipefds.rd > 1)
6743 close(pipefds.rd);
6744 /* Like bash, explicit redirects override pipes,
6745 * and the pipe fd is available for dup'ing. */
6746 if (setup_redirects(command, NULL))
6747 _exit(1);
6748
6749 /* Restore default handlers just prior to exec */
6750 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6751
6752 /* Stores to nommu_save list of env vars putenv'ed
6753 * (NOMMU, on MMU we don't need that) */
6754 /* cast away volatility... */
6755 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6756 /* pseudo_exec() does not return */
6757 }
6758
6759 /* parent or error */
6760#if ENABLE_HUSH_FAST
6761 G.count_SIGCHLD++;
6762//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6763#endif
6764 enable_restore_tty_pgrp_on_exit();
6765#if !BB_MMU
6766 /* Clean up after vforked child */
6767 free(nommu_save.argv);
6768 free(nommu_save.argv_from_re_execing);
6769 unset_vars(nommu_save.new_env);
6770 add_vars(nommu_save.old_vars);
6771#endif
6772 free(argv_expanded);
6773 argv_expanded = NULL;
6774 if (command->pid < 0) { /* [v]fork failed */
6775 /* Clearly indicate, was it fork or vfork */
6776 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6777 } else {
6778 pi->alive_cmds++;
6779#if ENABLE_HUSH_JOB
6780 /* Second and next children need to know pid of first one */
6781 if (pi->pgrp < 0)
6782 pi->pgrp = command->pid;
6783#endif
6784 }
6785
6786 if (cmd_no > 1)
6787 close(next_infd);
6788 if (cmd_no < pi->num_cmds)
6789 close(pipefds.wr);
6790 /* Pass read (output) pipe end to next iteration */
6791 next_infd = pipefds.rd;
6792 }
6793
6794 if (!pi->alive_cmds) {
6795 debug_leave();
6796 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6797 return 1;
6798 }
6799
6800 debug_leave();
6801 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6802 return -1;
6803}
6804
6805#ifndef debug_print_tree
6806static void debug_print_tree(struct pipe *pi, int lvl)
6807{
6808 static const char *const PIPE[] = {
6809 [PIPE_SEQ] = "SEQ",
6810 [PIPE_AND] = "AND",
6811 [PIPE_OR ] = "OR" ,
6812 [PIPE_BG ] = "BG" ,
6813 };
6814 static const char *RES[] = {
6815 [RES_NONE ] = "NONE" ,
6816# if ENABLE_HUSH_IF
6817 [RES_IF ] = "IF" ,
6818 [RES_THEN ] = "THEN" ,
6819 [RES_ELIF ] = "ELIF" ,
6820 [RES_ELSE ] = "ELSE" ,
6821 [RES_FI ] = "FI" ,
6822# endif
6823# if ENABLE_HUSH_LOOPS
6824 [RES_FOR ] = "FOR" ,
6825 [RES_WHILE] = "WHILE",
6826 [RES_UNTIL] = "UNTIL",
6827 [RES_DO ] = "DO" ,
6828 [RES_DONE ] = "DONE" ,
6829# endif
6830# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6831 [RES_IN ] = "IN" ,
6832# endif
6833# if ENABLE_HUSH_CASE
6834 [RES_CASE ] = "CASE" ,
6835 [RES_CASE_IN ] = "CASE_IN" ,
6836 [RES_MATCH] = "MATCH",
6837 [RES_CASE_BODY] = "CASE_BODY",
6838 [RES_ESAC ] = "ESAC" ,
6839# endif
6840 [RES_XXXX ] = "XXXX" ,
6841 [RES_SNTX ] = "SNTX" ,
6842 };
6843 static const char *const CMDTYPE[] = {
6844 "{}",
6845 "()",
6846 "[noglob]",
6847# if ENABLE_HUSH_FUNCTIONS
6848 "func()",
6849# endif
6850 };
6851
6852 int pin, prn;
6853
6854 pin = 0;
6855 while (pi) {
6856 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6857 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6858 prn = 0;
6859 while (prn < pi->num_cmds) {
6860 struct command *command = &pi->cmds[prn];
6861 char **argv = command->argv;
6862
6863 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6864 lvl*2, "", prn,
6865 command->assignment_cnt);
6866 if (command->group) {
6867 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6868 CMDTYPE[command->cmd_type],
6869 argv
6870# if !BB_MMU
6871 , " group_as_string:", command->group_as_string
6872# else
6873 , "", ""
6874# endif
6875 );
6876 debug_print_tree(command->group, lvl+1);
6877 prn++;
6878 continue;
6879 }
6880 if (argv) while (*argv) {
6881 fprintf(stderr, " '%s'", *argv);
6882 argv++;
6883 }
6884 fprintf(stderr, "\n");
6885 prn++;
6886 }
6887 pi = pi->next;
6888 pin++;
6889 }
6890}
6891#endif /* debug_print_tree */
6892
6893/* NB: called by pseudo_exec, and therefore must not modify any
6894 * global data until exec/_exit (we can be a child after vfork!) */
6895static int run_list(struct pipe *pi)
6896{
6897#if ENABLE_HUSH_CASE
6898 char *case_word = NULL;
6899#endif
6900#if ENABLE_HUSH_LOOPS
6901 struct pipe *loop_top = NULL;
6902 char **for_lcur = NULL;
6903 char **for_list = NULL;
6904#endif
6905 smallint last_followup;
6906 smalluint rcode;
6907#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6908 smalluint cond_code = 0;
6909#else
6910 enum { cond_code = 0 };
6911#endif
6912#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02006913 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006914 smallint last_rword; /* ditto */
6915#endif
6916
6917 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6918 debug_enter();
6919
6920#if ENABLE_HUSH_LOOPS
6921 /* Check syntax for "for" */
6922 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6923 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6924 continue;
6925 /* current word is FOR or IN (BOLD in comments below) */
6926 if (cpipe->next == NULL) {
6927 syntax_error("malformed for");
6928 debug_leave();
6929 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6930 return 1;
6931 }
6932 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6933 if (cpipe->next->res_word == RES_DO)
6934 continue;
6935 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6936 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6937 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6938 ) {
6939 syntax_error("malformed for");
6940 debug_leave();
6941 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6942 return 1;
6943 }
6944 }
6945#endif
6946
6947 /* Past this point, all code paths should jump to ret: label
6948 * in order to return, no direct "return" statements please.
6949 * This helps to ensure that no memory is leaked. */
6950
6951#if ENABLE_HUSH_JOB
6952 G.run_list_level++;
6953#endif
6954
6955#if HAS_KEYWORDS
6956 rword = RES_NONE;
6957 last_rword = RES_XXXX;
6958#endif
6959 last_followup = PIPE_SEQ;
6960 rcode = G.last_exitcode;
6961
6962 /* Go through list of pipes, (maybe) executing them. */
6963 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6964 if (G.flag_SIGINT)
6965 break;
6966
6967 IF_HAS_KEYWORDS(rword = pi->res_word;)
6968 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6969 rword, cond_code, last_rword);
6970#if ENABLE_HUSH_LOOPS
6971 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6972 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6973 ) {
6974 /* start of a loop: remember where loop starts */
6975 loop_top = pi;
6976 G.depth_of_loop++;
6977 }
6978#endif
6979 /* Still in the same "if...", "then..." or "do..." branch? */
6980 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6981 if ((rcode == 0 && last_followup == PIPE_OR)
6982 || (rcode != 0 && last_followup == PIPE_AND)
6983 ) {
6984 /* It is "<true> || CMD" or "<false> && CMD"
6985 * and we should not execute CMD */
6986 debug_printf_exec("skipped cmd because of || or &&\n");
6987 last_followup = pi->followup;
6988 continue;
6989 }
6990 }
6991 last_followup = pi->followup;
6992 IF_HAS_KEYWORDS(last_rword = rword;)
6993#if ENABLE_HUSH_IF
6994 if (cond_code) {
6995 if (rword == RES_THEN) {
6996 /* if false; then ... fi has exitcode 0! */
6997 G.last_exitcode = rcode = EXIT_SUCCESS;
6998 /* "if <false> THEN cmd": skip cmd */
6999 continue;
7000 }
7001 } else {
7002 if (rword == RES_ELSE || rword == RES_ELIF) {
7003 /* "if <true> then ... ELSE/ELIF cmd":
7004 * skip cmd and all following ones */
7005 break;
7006 }
7007 }
7008#endif
7009#if ENABLE_HUSH_LOOPS
7010 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7011 if (!for_lcur) {
7012 /* first loop through for */
7013
7014 static const char encoded_dollar_at[] ALIGN1 = {
7015 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7016 }; /* encoded representation of "$@" */
7017 static const char *const encoded_dollar_at_argv[] = {
7018 encoded_dollar_at, NULL
7019 }; /* argv list with one element: "$@" */
7020 char **vals;
7021
7022 vals = (char**)encoded_dollar_at_argv;
7023 if (pi->next->res_word == RES_IN) {
7024 /* if no variable values after "in" we skip "for" */
7025 if (!pi->next->cmds[0].argv) {
7026 G.last_exitcode = rcode = EXIT_SUCCESS;
7027 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7028 break;
7029 }
7030 vals = pi->next->cmds[0].argv;
7031 } /* else: "for var; do..." -> assume "$@" list */
7032 /* create list of variable values */
7033 debug_print_strings("for_list made from", vals);
7034 for_list = expand_strvec_to_strvec(vals);
7035 for_lcur = for_list;
7036 debug_print_strings("for_list", for_list);
7037 }
7038 if (!*for_lcur) {
7039 /* "for" loop is over, clean up */
7040 free(for_list);
7041 for_list = NULL;
7042 for_lcur = NULL;
7043 break;
7044 }
7045 /* Insert next value from for_lcur */
7046 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7047 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7048 continue;
7049 }
7050 if (rword == RES_IN) {
7051 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7052 }
7053 if (rword == RES_DONE) {
7054 continue; /* "done" has no cmds too */
7055 }
7056#endif
7057#if ENABLE_HUSH_CASE
7058 if (rword == RES_CASE) {
7059 case_word = expand_strvec_to_string(pi->cmds->argv);
7060 continue;
7061 }
7062 if (rword == RES_MATCH) {
7063 char **argv;
7064
7065 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7066 break;
7067 /* all prev words didn't match, does this one match? */
7068 argv = pi->cmds->argv;
7069 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007070 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007071 /* TODO: which FNM_xxx flags to use? */
7072 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7073 free(pattern);
7074 if (cond_code == 0) { /* match! we will execute this branch */
7075 free(case_word); /* make future "word)" stop */
7076 case_word = NULL;
7077 break;
7078 }
7079 argv++;
7080 }
7081 continue;
7082 }
7083 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7084 if (cond_code != 0)
7085 continue; /* not matched yet, skip this pipe */
7086 }
7087#endif
7088 /* Just pressing <enter> in shell should check for jobs.
7089 * OTOH, in non-interactive shell this is useless
7090 * and only leads to extra job checks */
7091 if (pi->num_cmds == 0) {
7092 if (G_interactive_fd)
7093 goto check_jobs_and_continue;
7094 continue;
7095 }
7096
7097 /* After analyzing all keywords and conditions, we decided
7098 * to execute this pipe. NB: have to do checkjobs(NULL)
7099 * after run_pipe to collect any background children,
7100 * even if list execution is to be stopped. */
7101 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7102 {
7103 int r;
7104#if ENABLE_HUSH_LOOPS
7105 G.flag_break_continue = 0;
7106#endif
7107 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7108 if (r != -1) {
7109 /* We ran a builtin, function, or group.
7110 * rcode is already known
7111 * and we don't need to wait for anything. */
7112 G.last_exitcode = rcode;
7113 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7114 check_and_run_traps(0);
7115#if ENABLE_HUSH_LOOPS
7116 /* Was it "break" or "continue"? */
7117 if (G.flag_break_continue) {
7118 smallint fbc = G.flag_break_continue;
7119 /* We might fall into outer *loop*,
7120 * don't want to break it too */
7121 if (loop_top) {
7122 G.depth_break_continue--;
7123 if (G.depth_break_continue == 0)
7124 G.flag_break_continue = 0;
7125 /* else: e.g. "continue 2" should *break* once, *then* continue */
7126 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7127 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7128 goto check_jobs_and_break;
7129 /* "continue": simulate end of loop */
7130 rword = RES_DONE;
7131 continue;
7132 }
7133#endif
7134#if ENABLE_HUSH_FUNCTIONS
7135 if (G.flag_return_in_progress == 1) {
7136 /* same as "goto check_jobs_and_break" */
7137 checkjobs(NULL);
7138 break;
7139 }
7140#endif
7141 } else if (pi->followup == PIPE_BG) {
7142 /* What does bash do with attempts to background builtins? */
7143 /* even bash 3.2 doesn't do that well with nested bg:
7144 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7145 * I'm NOT treating inner &'s as jobs */
7146 check_and_run_traps(0);
7147#if ENABLE_HUSH_JOB
7148 if (G.run_list_level == 1)
7149 insert_bg_job(pi);
7150#endif
7151 /* Last command's pid goes to $! */
7152 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7153 G.last_exitcode = rcode = EXIT_SUCCESS;
7154 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7155 } else {
7156#if ENABLE_HUSH_JOB
7157 if (G.run_list_level == 1 && G_interactive_fd) {
7158 /* Waits for completion, then fg's main shell */
7159 rcode = checkjobs_and_fg_shell(pi);
7160 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7161 check_and_run_traps(0);
7162 } else
7163#endif
7164 { /* This one just waits for completion */
7165 rcode = checkjobs(pi);
7166 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7167 check_and_run_traps(0);
7168 }
7169 G.last_exitcode = rcode;
7170 }
7171 }
7172
7173 /* Analyze how result affects subsequent commands */
7174#if ENABLE_HUSH_IF
7175 if (rword == RES_IF || rword == RES_ELIF)
7176 cond_code = rcode;
7177#endif
7178#if ENABLE_HUSH_LOOPS
7179 /* Beware of "while false; true; do ..."! */
7180 if (pi->next && pi->next->res_word == RES_DO) {
7181 if (rword == RES_WHILE) {
7182 if (rcode) {
7183 /* "while false; do...done" - exitcode 0 */
7184 G.last_exitcode = rcode = EXIT_SUCCESS;
7185 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7186 goto check_jobs_and_break;
7187 }
7188 }
7189 if (rword == RES_UNTIL) {
7190 if (!rcode) {
7191 debug_printf_exec(": until expr is true: breaking\n");
7192 check_jobs_and_break:
7193 checkjobs(NULL);
7194 break;
7195 }
7196 }
7197 }
7198#endif
7199
7200 check_jobs_and_continue:
7201 checkjobs(NULL);
7202 } /* for (pi) */
7203
7204#if ENABLE_HUSH_JOB
7205 G.run_list_level--;
7206#endif
7207#if ENABLE_HUSH_LOOPS
7208 if (loop_top)
7209 G.depth_of_loop--;
7210 free(for_list);
7211#endif
7212#if ENABLE_HUSH_CASE
7213 free(case_word);
7214#endif
7215 debug_leave();
7216 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7217 return rcode;
7218}
7219
7220/* Select which version we will use */
7221static int run_and_free_list(struct pipe *pi)
7222{
7223 int rcode = 0;
7224 debug_printf_exec("run_and_free_list entered\n");
7225 if (!G.n_mode) {
7226 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7227 rcode = run_list(pi);
7228 }
7229 /* free_pipe_list has the side effect of clearing memory.
7230 * In the long run that function can be merged with run_list,
7231 * but doing that now would hobble the debugging effort. */
7232 free_pipe_list(pi);
7233 debug_printf_exec("run_and_free_list return %d\n", rcode);
7234 return rcode;
7235}
7236
7237
Denis Vlasenkof9375282009-04-05 19:13:39 +00007238/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007239static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007240{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007241 unsigned sig;
7242 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007243 sigset_t old_blocked_set;
7244
7245 if (!G.inherited_set_is_saved) {
7246 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7247 G.inherited_set = G.blocked_set;
7248 }
7249 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007250
Denis Vlasenkof9375282009-04-05 19:13:39 +00007251 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007252 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007253 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007254 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007255 mask |= SPECIAL_JOB_SIGS;
7256 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007257 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007258
Denis Vlasenkof9375282009-04-05 19:13:39 +00007259 sig = 0;
7260 while (mask) {
7261 if (mask & 1)
7262 sigaddset(&G.blocked_set, sig);
7263 mask >>= 1;
7264 sig++;
7265 }
7266 sigdelset(&G.blocked_set, SIGCHLD);
7267
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007268 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7269 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7270
Denis Vlasenkof9375282009-04-05 19:13:39 +00007271 /* POSIX allows shell to re-enable SIGCHLD
7272 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007273#if ENABLE_HUSH_FAST
7274 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007275 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007276 signal(SIGCHLD, SIGCHLD_handler);
7277#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007278 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007279 signal(SIGCHLD, SIG_DFL);
7280#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007281
7282 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007283}
7284
7285#if ENABLE_HUSH_JOB
7286/* helper */
7287static void maybe_set_to_sigexit(int sig)
7288{
7289 void (*handler)(int);
7290 /* non_DFL_mask'ed signals are, well, masked,
7291 * no need to set handler for them.
7292 */
7293 if (!((G.non_DFL_mask >> sig) & 1)) {
7294 handler = signal(sig, sigexit);
7295 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7296 signal(sig, handler);
7297 }
7298}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007299/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007300static void set_fatal_handlers(void)
7301{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007302 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007303 if (HUSH_DEBUG) {
7304 maybe_set_to_sigexit(SIGILL );
7305 maybe_set_to_sigexit(SIGFPE );
7306 maybe_set_to_sigexit(SIGBUS );
7307 maybe_set_to_sigexit(SIGSEGV);
7308 maybe_set_to_sigexit(SIGTRAP);
7309 } /* else: hush is perfect. what SEGV? */
7310 maybe_set_to_sigexit(SIGABRT);
7311 /* bash 3.2 seems to handle these just like 'fatal' ones */
7312 maybe_set_to_sigexit(SIGPIPE);
7313 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007314 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007315 * if we aren't interactive... but in this case
7316 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007317 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007318 /*maybe_set_to_sigexit(SIGTERM);*/
7319 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007320}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007321#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007322
Denis Vlasenkod5762932009-03-31 11:22:57 +00007323static int set_mode(const char cstate, const char mode)
7324{
7325 int state = (cstate == '-' ? 1 : 0);
7326 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007327 case 'n': G.n_mode = state; break;
7328 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007329 default: return EXIT_FAILURE;
7330 }
7331 return EXIT_SUCCESS;
7332}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007333
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007334int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007335int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007336{
7337 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007338 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007339 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007340 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00007341
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007342 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007343 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007344 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007345#if !BB_MMU
7346 G.argv0_for_re_execing = argv[0];
7347#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007348 /* Deal with HUSH_VERSION */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007349 G.shell_ver.flg_export = 1;
7350 G.shell_ver.flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007351 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007352 * therefore we xstrdup: */
7353 G.shell_ver.varstr = xstrdup(hush_version_str),
Denis Vlasenko87a86552008-07-29 19:43:10 +00007354 G.top_var = &G.shell_ver;
Denys Vlasenko605067b2010-09-06 12:10:51 +02007355 /* Create shell local variables from the values
7356 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007357 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007358 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007359 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007360 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007361 if (e) while (*e) {
7362 char *value = strchr(*e, '=');
7363 if (value) { /* paranoia */
7364 cur_var->next = xzalloc(sizeof(*cur_var));
7365 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007366 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007367 cur_var->max_len = strlen(*e);
7368 cur_var->flg_export = 1;
7369 }
7370 e++;
7371 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007372 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7373 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7374 putenv(G.shell_ver.varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007375
7376 /* Export PWD */
7377 set_pwd_var(/*exp:*/ 1);
7378 /* bash also exports SHLVL and _,
7379 * and sets (but doesn't export) the following variables:
7380 * BASH=/bin/bash
7381 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7382 * BASH_VERSION='3.2.0(1)-release'
7383 * HOSTTYPE=i386
7384 * MACHTYPE=i386-pc-linux-gnu
7385 * OSTYPE=linux-gnu
7386 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007387 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007388 * EUID=<NNNNN>
7389 * UID=<NNNNN>
7390 * GROUPS=()
7391 * LINES=<NNN>
7392 * COLUMNS=<NNN>
7393 * BASH_ARGC=()
7394 * BASH_ARGV=()
7395 * BASH_LINENO=()
7396 * BASH_SOURCE=()
7397 * DIRSTACK=()
7398 * PIPESTATUS=([0]="0")
7399 * HISTFILE=/<xxx>/.bash_history
7400 * HISTFILESIZE=500
7401 * HISTSIZE=500
7402 * MAILCHECK=60
7403 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7404 * SHELL=/bin/bash
7405 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7406 * TERM=dumb
7407 * OPTERR=1
7408 * OPTIND=1
7409 * IFS=$' \t\n'
7410 * PS1='\s-\v\$ '
7411 * PS2='> '
7412 * PS4='+ '
7413 */
7414
Denis Vlasenko38f63192007-01-22 09:03:07 +00007415#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007416 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007417#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007418 G.global_argc = argc;
7419 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007420 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007421 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007422
Denis Vlasenkoed782372009-04-10 00:45:02 +00007423 if (setjmp(die_jmp)) {
7424 /* xfunc has failed! die die die */
7425 /* no EXIT traps, this is an escape hatch! */
7426 G.exiting = 1;
7427 hush_exit(xfunc_error_retval);
7428 }
7429
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007430 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007431 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007432 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007433 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007434 * in order to intercept (more) signals.
7435 */
7436
7437 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007438 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007439 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007440 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007441 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007442#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007443 "<:$:R:V:"
7444# if ENABLE_HUSH_FUNCTIONS
7445 "F:"
7446# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007447#endif
7448 );
7449 if (opt <= 0)
7450 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007451 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007452 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007453 /* Possibilities:
7454 * sh ... -c 'script'
7455 * sh ... -c 'script' ARG0 [ARG1...]
7456 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007457 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007458 * "" needs to be replaced with NULL
7459 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007460 * Note: the form without ARG0 never happens:
7461 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007462 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007463 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007464 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007465 G.root_ppid = getppid();
7466 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007467 G.global_argv = argv + optind;
7468 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007469 if (builtin_argc) {
7470 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7471 const struct built_in_command *x;
7472
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007473 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007474 x = find_builtin(optarg);
7475 if (x) { /* paranoia */
7476 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7477 G.global_argv += builtin_argc;
7478 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007479 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007480 }
7481 goto final_return;
7482 }
7483 if (!G.global_argv[0]) {
7484 /* -c 'script' (no params): prevent empty $0 */
7485 G.global_argv--; /* points to argv[i] of 'script' */
7486 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007487 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007488 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007489 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007490 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007491 goto final_return;
7492 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007493 /* Well, we cannot just declare interactiveness,
7494 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007495 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007496 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007497 case 's':
7498 /* "-s" means "read from stdin", but this is how we always
7499 * operate, so simply do nothing here. */
7500 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007501#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007502 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007503 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007504 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007505 case '$': {
7506 unsigned long long empty_trap_mask;
7507
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007508 G.root_pid = bb_strtou(optarg, &optarg, 16);
7509 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007510 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7511 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007512 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7513 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007514 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007515 optarg++;
7516 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007517 optarg++;
7518 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7519 if (empty_trap_mask != 0) {
7520 int sig;
7521 init_sigmasks();
7522 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7523 for (sig = 1; sig < NSIG; sig++) {
7524 if (empty_trap_mask & (1LL << sig)) {
7525 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7526 sigaddset(&G.blocked_set, sig);
7527 }
7528 }
7529 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7530 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007531# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007532 optarg++;
7533 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007534# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007535 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007536 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007537 case 'R':
7538 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007539 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007540 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007541# if ENABLE_HUSH_FUNCTIONS
7542 case 'F': {
7543 struct function *funcp = new_function(optarg);
7544 /* funcp->name is already set to optarg */
7545 /* funcp->body is set to NULL. It's a special case. */
7546 funcp->body_as_string = argv[optind];
7547 optind++;
7548 break;
7549 }
7550# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007551#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007552 case 'n':
7553 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007554 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007555 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007556 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007557#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007558 fprintf(stderr, "Usage: sh [FILE]...\n"
7559 " or: sh -c command [args]...\n\n");
7560 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007561#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007562 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007563#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007564 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007565 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007566
Denys Vlasenkodea47882009-10-09 15:40:49 +02007567 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007568 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007569 G.root_ppid = getppid();
7570 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007571
7572 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007573 if (argv[0] && argv[0][0] == '-') {
7574 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007575 debug_printf("sourcing /etc/profile\n");
7576 input = fopen_for_read("/etc/profile");
7577 if (input != NULL) {
7578 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007579 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007580 parse_and_run_file(input);
7581 fclose(input);
7582 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007583 /* bash: after sourcing /etc/profile,
7584 * tries to source (in the given order):
7585 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007586 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007587 * bash also sources ~/.bash_logout on exit.
7588 * If called as sh, skips .bash_XXX files.
7589 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007590 }
7591
Denis Vlasenkof9375282009-04-05 19:13:39 +00007592 if (argv[optind]) {
7593 FILE *input;
7594 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007595 * "bash <script>" (which is never interactive (unless -i?))
7596 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007597 * If called as sh, does the same but with $ENV.
7598 */
7599 debug_printf("running script '%s'\n", argv[optind]);
7600 G.global_argv = argv + optind;
7601 G.global_argc = argc - optind;
7602 input = xfopen_for_read(argv[optind]);
7603 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007604 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007605 parse_and_run_file(input);
7606#if ENABLE_FEATURE_CLEAN_UP
7607 fclose(input);
7608#endif
7609 goto final_return;
7610 }
7611
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007612 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007613 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007614 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007615
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007616 /* A shell is interactive if the '-i' flag was given,
7617 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007618 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007619 * no arguments remaining or the -s flag given
7620 * standard input is a terminal
7621 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007622 * Refer to Posix.2, the description of the 'sh' utility.
7623 */
7624#if ENABLE_HUSH_JOB
7625 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007626 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7627 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7628 if (G_saved_tty_pgrp < 0)
7629 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007630
7631 /* try to dup stdin to high fd#, >= 255 */
7632 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7633 if (G_interactive_fd < 0) {
7634 /* try to dup to any fd */
7635 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007636 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007637 /* give up */
7638 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007639 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007640 }
7641 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007642// TODO: track & disallow any attempts of user
7643// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007644 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007645 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007646 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007647 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007648
Mike Frysinger38478a62009-05-20 04:48:06 -04007649 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007650 /* If we were run as 'hush &', sleep until we are
7651 * in the foreground (tty pgrp == our pgrp).
7652 * If we get started under a job aware app (like bash),
7653 * make sure we are now in charge so we don't fight over
7654 * who gets the foreground */
7655 while (1) {
7656 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007657 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7658 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007659 break;
7660 /* send TTIN to ourself (should stop us) */
7661 kill(- shell_pgrp, SIGTTIN);
7662 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007663 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007664
Denis Vlasenkof9375282009-04-05 19:13:39 +00007665 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007666 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007667
Mike Frysinger38478a62009-05-20 04:48:06 -04007668 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007669 /* Set other signals to restore saved_tty_pgrp */
7670 set_fatal_handlers();
7671 /* Put ourselves in our own process group
7672 * (bash, too, does this only if ctty is available) */
7673 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7674 /* Grab control of the terminal */
7675 tcsetpgrp(G_interactive_fd, getpid());
7676 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007677 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007678 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007679 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007680 } else {
7681 init_sigmasks();
7682 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007683#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007684 /* No job control compiled in, only prompt/line editing */
7685 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007686 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7687 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007688 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007689 G_interactive_fd = dup(STDIN_FILENO);
7690 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007691 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007692 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007693 }
7694 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007695 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007696 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007697 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007698 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007699#else
7700 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007701 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007702#endif
7703 /* bash:
7704 * if interactive but not a login shell, sources ~/.bashrc
7705 * (--norc turns this off, --rcfile <file> overrides)
7706 */
7707
7708 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007709 /* note: ash and hush share this string */
7710 printf("\n\n%s %s\n"
7711 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7712 "\n",
7713 bb_banner,
7714 "hush - the humble shell"
7715 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007716 }
7717
Denis Vlasenkof9375282009-04-05 19:13:39 +00007718 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007719
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007720 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007721#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007722 if (G.cwd != bb_msg_unknown)
7723 free((char*)G.cwd);
7724 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007725 while (cur_var) {
7726 struct variable *tmp = cur_var;
7727 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007728 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007729 cur_var = cur_var->next;
7730 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007731 }
Eric Andersen25f27032001-04-26 23:22:31 +00007732#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007733 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007734}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007735
7736
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007737#if ENABLE_MSH
7738int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7739int msh_main(int argc, char **argv)
7740{
7741 //bb_error_msg("msh is deprecated, please use hush instead");
7742 return hush_main(argc, argv);
7743}
7744#endif
7745
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007746
7747/*
7748 * Built-ins
7749 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007750static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007751{
7752 return 0;
7753}
7754
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007755static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007756{
7757 int argc = 0;
7758 while (*argv) {
7759 argc++;
7760 argv++;
7761 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007762 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007763}
7764
7765static int FAST_FUNC builtin_test(char **argv)
7766{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007767 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007768}
7769
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007770static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007771{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007772 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007773}
7774
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007775#if ENABLE_PRINTF
7776static int FAST_FUNC builtin_printf(char **argv)
7777{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007778 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007779}
7780#endif
7781
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007782static char **skip_dash_dash(char **argv)
7783{
7784 argv++;
7785 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7786 argv++;
7787 return argv;
7788}
7789
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007790static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007791{
7792 int rcode = EXIT_SUCCESS;
7793
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007794 argv = skip_dash_dash(argv);
7795 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007796 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007797 /* bash:
7798 * eval "echo Hi; done" ("done" is syntax error):
7799 * "echo Hi" will not execute too.
7800 */
7801 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007802 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007803 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007804 }
7805 return rcode;
7806}
7807
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007808static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007809{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007810 const char *newdir;
7811
7812 argv = skip_dash_dash(argv);
7813 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007814 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007815 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007816 * bash says "bash: cd: HOME not set" and does nothing
7817 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007818 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007819 const char *home = get_local_var_value("HOME");
7820 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007821 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007822 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007823 /* Mimic bash message exactly */
7824 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007825 return EXIT_FAILURE;
7826 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007827 /* Read current dir (get_cwd(1) is inside) and set PWD.
7828 * Note: do not enforce exporting. If PWD was unset or unexported,
7829 * set it again, but do not export. bash does the same.
7830 */
7831 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007832 return EXIT_SUCCESS;
7833}
7834
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007835static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007836{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007837 argv = skip_dash_dash(argv);
7838 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007839 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007840
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007841 /* Careful: we can end up here after [v]fork. Do not restore
7842 * tty pgrp then, only top-level shell process does that */
7843 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7844 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7845
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007846 /* TODO: if exec fails, bash does NOT exit! We do.
7847 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7848 * and tcsetpgrp, and this is inherently racy.
7849 */
7850 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007851}
7852
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007853static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007854{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007855 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007856
7857 /* interactive bash:
7858 * # trap "echo EEE" EXIT
7859 * # exit
7860 * exit
7861 * There are stopped jobs.
7862 * (if there are _stopped_ jobs, running ones don't count)
7863 * # exit
7864 * exit
7865 # EEE (then bash exits)
7866 *
7867 * we can use G.exiting = -1 as indicator "last cmd was exit"
7868 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007869
7870 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007871 argv = skip_dash_dash(argv);
7872 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007873 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007874 /* mimic bash: exit 123abc == exit 255 + error msg */
7875 xfunc_error_retval = 255;
7876 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007877 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007878}
7879
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007880static void print_escaped(const char *s)
7881{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007882 if (*s == '\'')
7883 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007884 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007885 const char *p = strchrnul(s, '\'');
7886 /* print 'xxxx', possibly just '' */
7887 printf("'%.*s'", (int)(p - s), s);
7888 if (*p == '\0')
7889 break;
7890 s = p;
7891 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007892 /* s points to '; print "'''...'''" */
7893 putchar('"');
7894 do putchar('\''); while (*++s == '\'');
7895 putchar('"');
7896 } while (*s);
7897}
7898
Denys Vlasenko295fef82009-06-03 12:47:26 +02007899#if !ENABLE_HUSH_LOCAL
7900#define helper_export_local(argv, exp, lvl) \
7901 helper_export_local(argv, exp)
7902#endif
7903static void helper_export_local(char **argv, int exp, int lvl)
7904{
7905 do {
7906 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007907 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02007908
7909 /* So far we do not check that name is valid (TODO?) */
7910
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007911 if (*name_end == '\0') {
7912 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02007913
Denys Vlasenko27c56f12010-09-07 09:56:34 +02007914 vpp = get_ptr_to_local_var(name, name_end - name);
7915 var = vpp ? *vpp : NULL;
7916
Denys Vlasenko295fef82009-06-03 12:47:26 +02007917 if (exp == -1) { /* unexporting? */
7918 /* export -n NAME (without =VALUE) */
7919 if (var) {
7920 var->flg_export = 0;
7921 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7922 unsetenv(name);
7923 } /* else: export -n NOT_EXISTING_VAR: no-op */
7924 continue;
7925 }
7926 if (exp == 1) { /* exporting? */
7927 /* export NAME (without =VALUE) */
7928 if (var) {
7929 var->flg_export = 1;
7930 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7931 putenv(var->varstr);
7932 continue;
7933 }
7934 }
7935 /* Exporting non-existing variable.
7936 * bash does not put it in environment,
7937 * but remembers that it is exported,
7938 * and does put it in env when it is set later.
7939 * We just set it to "" and export. */
7940 /* Or, it's "local NAME" (without =VALUE).
7941 * bash sets the value to "". */
7942 name = xasprintf("%s=", name);
7943 } else {
7944 /* (Un)exporting/making local NAME=VALUE */
7945 name = xstrdup(name);
7946 }
7947 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7948 } while (*++argv);
7949}
7950
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007951static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007952{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007953 unsigned opt_unexport;
7954
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007955#if ENABLE_HUSH_EXPORT_N
7956 /* "!": do not abort on errors */
7957 opt_unexport = getopt32(argv, "!n");
7958 if (opt_unexport == (uint32_t)-1)
7959 return EXIT_FAILURE;
7960 argv += optind;
7961#else
7962 opt_unexport = 0;
7963 argv++;
7964#endif
7965
7966 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007967 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007968 if (e) {
7969 while (*e) {
7970#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007971 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007972#else
7973 /* ash emits: export VAR='VAL'
7974 * bash: declare -x VAR="VAL"
7975 * we follow ash example */
7976 const char *s = *e++;
7977 const char *p = strchr(s, '=');
7978
7979 if (!p) /* wtf? take next variable */
7980 continue;
7981 /* export var= */
7982 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007983 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007984 putchar('\n');
7985#endif
7986 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007987 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007988 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007989 return EXIT_SUCCESS;
7990 }
7991
Denys Vlasenko295fef82009-06-03 12:47:26 +02007992 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007993
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007994 return EXIT_SUCCESS;
7995}
7996
Denys Vlasenko295fef82009-06-03 12:47:26 +02007997#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007998static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007999{
8000 if (G.func_nest_level == 0) {
8001 bb_error_msg("%s: not in a function", argv[0]);
8002 return EXIT_FAILURE; /* bash compat */
8003 }
8004 helper_export_local(argv, 0, G.func_nest_level);
8005 return EXIT_SUCCESS;
8006}
8007#endif
8008
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008009static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008010{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008011 int sig;
8012 char *new_cmd;
8013
8014 if (!G.traps)
8015 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8016
8017 argv++;
8018 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008019 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008020 /* No args: print all trapped */
8021 for (i = 0; i < NSIG; ++i) {
8022 if (G.traps[i]) {
8023 printf("trap -- ");
8024 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008025 /* note: bash adds "SIG", but only if invoked
8026 * as "bash". If called as "sh", or if set -o posix,
8027 * then it prints short signal names.
8028 * We are printing short names: */
8029 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008030 }
8031 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008032 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008033 return EXIT_SUCCESS;
8034 }
8035
8036 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008037 /* If first arg is a number: reset all specified signals */
8038 sig = bb_strtou(*argv, NULL, 10);
8039 if (errno == 0) {
8040 int ret;
8041 process_sig_list:
8042 ret = EXIT_SUCCESS;
8043 while (*argv) {
8044 sig = get_signum(*argv++);
8045 if (sig < 0 || sig >= NSIG) {
8046 ret = EXIT_FAILURE;
8047 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008048 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008049 continue;
8050 }
8051
8052 free(G.traps[sig]);
8053 G.traps[sig] = xstrdup(new_cmd);
8054
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008055 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008056 get_signame(sig), sig, G.traps[sig]);
8057
8058 /* There is no signal for 0 (EXIT) */
8059 if (sig == 0)
8060 continue;
8061
8062 if (new_cmd) {
8063 sigaddset(&G.blocked_set, sig);
8064 } else {
8065 /* There was a trap handler, we are removing it
8066 * (if sig has non-DFL handling,
8067 * we don't need to do anything) */
8068 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8069 continue;
8070 sigdelset(&G.blocked_set, sig);
8071 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008072 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008073 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008074 return ret;
8075 }
8076
8077 if (!argv[1]) { /* no second arg */
8078 bb_error_msg("trap: invalid arguments");
8079 return EXIT_FAILURE;
8080 }
8081
8082 /* First arg is "-": reset all specified to default */
8083 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8084 /* Everything else: set arg as signal handler
8085 * (includes "" case, which ignores signal) */
8086 if (argv[0][0] == '-') {
8087 if (argv[0][1] == '\0') { /* "-" */
8088 /* new_cmd remains NULL: "reset these sigs" */
8089 goto reset_traps;
8090 }
8091 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8092 argv++;
8093 }
8094 /* else: "-something", no special meaning */
8095 }
8096 new_cmd = *argv;
8097 reset_traps:
8098 argv++;
8099 goto process_sig_list;
8100}
8101
Mike Frysinger93cadc22009-05-27 17:06:25 -04008102/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008103static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008104{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008105 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008106
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008107 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008108 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008109 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008110
8111 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008112 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008113 type = "an alias";*/
8114#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008115 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008116 type = "a function";
8117#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008118 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008119 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008120 else if ((path = find_in_path(*argv)) != NULL)
8121 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008122 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008123 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008124 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008125 continue;
8126 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008127
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008128 printf("%s is %s\n", *argv, type);
8129 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008130 }
8131
8132 return ret;
8133}
8134
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008135#if ENABLE_HUSH_JOB
8136/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008137static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008138{
8139 int i, jobnum;
8140 struct pipe *pi;
8141
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008142 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008143 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008144
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008145 /* If they gave us no args, assume they want the last backgrounded task */
8146 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008147 for (pi = G.job_list; pi; pi = pi->next) {
8148 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008149 goto found;
8150 }
8151 }
8152 bb_error_msg("%s: no current job", argv[0]);
8153 return EXIT_FAILURE;
8154 }
8155 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8156 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8157 return EXIT_FAILURE;
8158 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008159 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008160 if (pi->jobid == jobnum) {
8161 goto found;
8162 }
8163 }
8164 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8165 return EXIT_FAILURE;
8166 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008167 /* TODO: bash prints a string representation
8168 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008169 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008170 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008171 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008172 }
8173
8174 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008175 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8176 for (i = 0; i < pi->num_cmds; i++) {
8177 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8178 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008179 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008180 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008181
8182 i = kill(- pi->pgrp, SIGCONT);
8183 if (i < 0) {
8184 if (errno == ESRCH) {
8185 delete_finished_bg_job(pi);
8186 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008187 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008188 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008189 }
8190
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008191 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008192 remove_bg_job(pi);
8193 return checkjobs_and_fg_shell(pi);
8194 }
8195 return EXIT_SUCCESS;
8196}
8197#endif
8198
8199#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008200static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008201{
8202 const struct built_in_command *x;
8203
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008204 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008205 "Built-in commands:\n"
8206 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008207 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008208 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008209 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008210 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008211 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008212 return EXIT_SUCCESS;
8213}
8214#endif
8215
8216#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008217static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008218{
8219 struct pipe *job;
8220 const char *status_string;
8221
Denis Vlasenko87a86552008-07-29 19:43:10 +00008222 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008223 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008224 status_string = "Stopped";
8225 else
8226 status_string = "Running";
8227
8228 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8229 }
8230 return EXIT_SUCCESS;
8231}
8232#endif
8233
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008234#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008235static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008236{
8237 void *p;
8238 unsigned long l;
8239
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008240# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008241 /* Optional. Reduces probability of false positives */
8242 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008243# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008244 /* Crude attempt to find where "free memory" starts,
8245 * sans fragmentation. */
8246 p = malloc(240);
8247 l = (unsigned long)p;
8248 free(p);
8249 p = malloc(3400);
8250 if (l < (unsigned long)p) l = (unsigned long)p;
8251 free(p);
8252
8253 if (!G.memleak_value)
8254 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008255
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008256 l -= G.memleak_value;
8257 if ((long)l < 0)
8258 l = 0;
8259 l /= 1024;
8260 if (l > 127)
8261 l = 127;
8262
8263 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8264 return l;
8265}
8266#endif
8267
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008268static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008269{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008270 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008271 return EXIT_SUCCESS;
8272}
8273
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008274static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008275{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008276 const char *r;
8277 char *opt_n = NULL;
8278 char *opt_p = NULL;
8279 char *opt_t = NULL;
8280 char *opt_u = NULL;
8281 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008282
Denys Vlasenko03dad222010-01-12 23:29:57 +01008283 /* "!": do not abort on errors.
8284 * Option string must start with "sr" to match BUILTIN_READ_xxx
8285 */
8286 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8287 if (read_flags == (uint32_t)-1)
8288 return EXIT_FAILURE;
8289 argv += optind;
8290
8291 r = shell_builtin_read(set_local_var_from_halves,
8292 argv,
8293 get_local_var_value("IFS"), /* can be NULL */
8294 read_flags,
8295 opt_n,
8296 opt_p,
8297 opt_t,
8298 opt_u
8299 );
8300
8301 if ((uintptr_t)r > 1) {
8302 bb_error_msg("%s", r);
8303 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008304 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008305
Denys Vlasenko03dad222010-01-12 23:29:57 +01008306 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008307}
8308
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008309/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8310 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008311 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008312 * set [-abCefhmnuvx] [-o option] [argument...]
8313 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008314 * set -- [argument...]
8315 * set -o
8316 * set +o
8317 * Implementations shall support the options in both their hyphen and
8318 * plus-sign forms. These options can also be specified as options to sh.
8319 * Examples:
8320 * Write out all variables and their values: set
8321 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8322 * Turn on the -x and -v options: set -xv
8323 * Unset all positional parameters: set --
8324 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8325 * Set the positional parameters to the expansion of x, even if x expands
8326 * with a leading '-' or '+': set -- $x
8327 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008328 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008329 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008330static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008331{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008332 int n;
8333 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008334 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008335
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008336 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008337 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008338 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008339 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008340 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008341 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008342
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008343 do {
8344 if (!strcmp(arg, "--")) {
8345 ++argv;
8346 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008347 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008348 if (arg[0] != '+' && arg[0] != '-')
8349 break;
8350 for (n = 1; arg[n]; ++n)
8351 if (set_mode(arg[0], arg[n]))
8352 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008353 } while ((arg = *++argv) != NULL);
8354 /* Now argv[0] is 1st argument */
8355
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008356 if (arg == NULL)
8357 return EXIT_SUCCESS;
8358 set_argv:
8359
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008360 /* NB: G.global_argv[0] ($0) is never freed/changed */
8361 g_argv = G.global_argv;
8362 if (G.global_args_malloced) {
8363 pp = g_argv;
8364 while (*++pp)
8365 free(*pp);
8366 g_argv[1] = NULL;
8367 } else {
8368 G.global_args_malloced = 1;
8369 pp = xzalloc(sizeof(pp[0]) * 2);
8370 pp[0] = g_argv[0]; /* retain $0 */
8371 g_argv = pp;
8372 }
8373 /* This realloc's G.global_argv */
8374 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8375
8376 n = 1;
8377 while (*++pp)
8378 n++;
8379 G.global_argc = n;
8380
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008381 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008382
8383 /* Nothing known, so abort */
8384 error:
8385 bb_error_msg("set: %s: invalid option", arg);
8386 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008387}
8388
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008389static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008390{
8391 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008392 argv = skip_dash_dash(argv);
8393 if (argv[0]) {
8394 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008395 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008396 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008397 if (G.global_args_malloced) {
8398 int m = 1;
8399 while (m <= n)
8400 free(G.global_argv[m++]);
8401 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008402 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008403 memmove(&G.global_argv[1], &G.global_argv[n+1],
8404 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008405 return EXIT_SUCCESS;
8406 }
8407 return EXIT_FAILURE;
8408}
8409
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008410static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008411{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008412 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008413 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008414 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008415#if ENABLE_HUSH_FUNCTIONS
8416 smallint sv_flg;
8417#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008418
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008419 argv = skip_dash_dash(argv);
8420 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008421 if (!filename) {
8422 /* bash says: "bash: .: filename argument required" */
8423 return 2; /* bash compat */
8424 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008425 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008426 if (!strchr(filename, '/')) {
8427 arg_path = find_in_path(filename);
8428 if (arg_path)
8429 filename = arg_path;
8430 }
8431 input = fopen_or_warn(filename, "r");
8432 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008433 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008434 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008435 return EXIT_FAILURE;
8436 }
8437 close_on_exec_on(fileno(input));
8438
Mike Frysinger885b6f22009-04-18 21:04:25 +00008439#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008440 sv_flg = G.flag_return_in_progress;
8441 /* "we are inside sourced file, ok to use return" */
8442 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008443#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008444 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008445
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008446 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008447 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008448
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008449 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008450#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008451 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008452#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008453
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008454 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008455}
8456
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008457static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008458{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008459 int rc;
8460 mode_t mask;
8461
8462 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008463 argv = skip_dash_dash(argv);
8464 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008465 mode_t old_mask = mask;
8466
8467 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008468 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008469 mask ^= 0777;
8470 if (rc == 0) {
8471 mask = old_mask;
8472 /* bash messages:
8473 * bash: umask: 'q': invalid symbolic mode operator
8474 * bash: umask: 999: octal number out of range
8475 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008476 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008477 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008478 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008479 rc = 1;
8480 /* Mimic bash */
8481 printf("%04o\n", (unsigned) mask);
8482 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008483 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008484 umask(mask);
8485
8486 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008487}
8488
Mike Frysingerd690f682009-03-30 06:50:54 +00008489/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008490static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008491{
Mike Frysingerd690f682009-03-30 06:50:54 +00008492 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008493 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008494
Denis Vlasenko28e67962009-04-26 23:22:40 +00008495 /* "!": do not abort on errors */
8496 /* "+": stop at 1st non-option */
8497 opts = getopt32(argv, "!+vf");
8498 if (opts == (unsigned)-1)
8499 return EXIT_FAILURE;
8500 if (opts == 3) {
8501 bb_error_msg("unset: -v and -f are exclusive");
8502 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008503 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008504 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008505
8506 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008507 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008508 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008509 if (unset_local_var(*argv)) {
8510 /* unset <nonexistent_var> doesn't fail.
8511 * Error is when one tries to unset RO var.
8512 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008513 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008514 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008515 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008516#if ENABLE_HUSH_FUNCTIONS
8517 else {
8518 unset_func(*argv);
8519 }
8520#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008521 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008522 }
8523 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008524}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008525
Mike Frysinger56bdea12009-03-28 20:01:58 +00008526/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008527static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008528{
8529 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008530 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008531
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008532 argv = skip_dash_dash(argv);
8533 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008534 /* Don't care about wait results */
8535 /* Note 1: must wait until there are no more children */
8536 /* Note 2: must be interruptible */
8537 /* Examples:
8538 * $ sleep 3 & sleep 6 & wait
8539 * [1] 30934 sleep 3
8540 * [2] 30935 sleep 6
8541 * [1] Done sleep 3
8542 * [2] Done sleep 6
8543 * $ sleep 3 & sleep 6 & wait
8544 * [1] 30936 sleep 3
8545 * [2] 30937 sleep 6
8546 * [1] Done sleep 3
8547 * ^C <-- after ~4 sec from keyboard
8548 * $
8549 */
8550 sigaddset(&G.blocked_set, SIGCHLD);
8551 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8552 while (1) {
8553 checkjobs(NULL);
8554 if (errno == ECHILD)
8555 break;
8556 /* Wait for SIGCHLD or any other signal of interest */
8557 /* sigtimedwait with infinite timeout: */
8558 sig = sigwaitinfo(&G.blocked_set, NULL);
8559 if (sig > 0) {
8560 sig = check_and_run_traps(sig);
8561 if (sig && sig != SIGCHLD) { /* see note 2 */
8562 ret = 128 + sig;
8563 break;
8564 }
8565 }
8566 }
8567 sigdelset(&G.blocked_set, SIGCHLD);
8568 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8569 return ret;
8570 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008571
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008572 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008573 while (*argv) {
8574 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008575 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008576 /* mimic bash message */
8577 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008578 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008579 }
8580 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008581 if (WIFSIGNALED(status))
8582 ret = 128 + WTERMSIG(status);
8583 else if (WIFEXITED(status))
8584 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008585 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008586 ret = EXIT_FAILURE;
8587 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008588 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008589 ret = 127;
8590 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008591 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008592 }
8593
8594 return ret;
8595}
8596
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008597#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8598static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8599{
8600 if (argv[1]) {
8601 def = bb_strtou(argv[1], NULL, 10);
8602 if (errno || def < def_min || argv[2]) {
8603 bb_error_msg("%s: bad arguments", argv[0]);
8604 def = UINT_MAX;
8605 }
8606 }
8607 return def;
8608}
8609#endif
8610
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008611#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008612static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008613{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008614 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008615 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008616 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008617 return EXIT_SUCCESS; /* bash compat */
8618 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008619 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008620
8621 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8622 if (depth == UINT_MAX)
8623 G.flag_break_continue = BC_BREAK;
8624 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008625 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008626
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008627 return EXIT_SUCCESS;
8628}
8629
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008630static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008631{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008632 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8633 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008634}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008635#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008636
8637#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008638static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008639{
8640 int rc;
8641
8642 if (G.flag_return_in_progress != -1) {
8643 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8644 return EXIT_FAILURE; /* bash compat */
8645 }
8646
8647 G.flag_return_in_progress = 1;
8648
8649 /* bash:
8650 * out of range: wraps around at 256, does not error out
8651 * non-numeric param:
8652 * f() { false; return qwe; }; f; echo $?
8653 * bash: return: qwe: numeric argument required <== we do this
8654 * 255 <== we also do this
8655 */
8656 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8657 return rc;
8658}
8659#endif