blob: 7645a34a4f8a1d351d4295ae872d1538b81369ab [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 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000081 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
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"
92#include "builtin_read.h"
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010093#include "builtin_ulimit.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000094#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000095#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +020096#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +020097# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +020098#else
99# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200100#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000101#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200102# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000103#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000104
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000105
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200106/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000107#define LEAK_HUNTING 0
108#define BUILD_AS_NOMMU 0
109/* Enable/disable sanity checks. Ok to enable in production,
110 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
111 * Keeping 1 for now even in released versions.
112 */
113#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200114/* Slightly bigger (+200 bytes), but faster hush.
115 * So far it only enables a trick with counting SIGCHLDs and forks,
116 * which allows us to do fewer waitpid's.
117 * (we can detect a case where neither forks were done nor SIGCHLDs happened
118 * and therefore waitpid will return the same result as last time)
119 */
120#define ENABLE_HUSH_FAST 0
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000121
122
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000123#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000124# undef BB_MMU
125# undef USE_FOR_NOMMU
126# undef USE_FOR_MMU
127# define BB_MMU 0
128# define USE_FOR_NOMMU(...) __VA_ARGS__
129# define USE_FOR_MMU(...)
130#endif
131
Denys Vlasenko14974842010-03-23 01:08:26 +0100132#define SKIP_definitions 1
133#include "applet_tables.h"
134#undef SKIP_definitions
135#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000136/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000137# undef CONFIG_FEATURE_SH_STANDALONE
138# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000139# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100140# undef IF_NOT_FEATURE_SH_STANDALONE
141# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000142# define IF_FEATURE_SH_STANDALONE(...)
143# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000144#endif
145
Denis Vlasenko05743d72008-02-10 12:10:08 +0000146#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000147# undef ENABLE_FEATURE_EDITING
148# define ENABLE_FEATURE_EDITING 0
149# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
150# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000151#endif
152
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000153/* Do we support ANY keywords? */
154#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000155# define HAS_KEYWORDS 1
156# define IF_HAS_KEYWORDS(...) __VA_ARGS__
157# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000158#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000159# define HAS_KEYWORDS 0
160# define IF_HAS_KEYWORDS(...)
161# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000162#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000163
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000164/* If you comment out one of these below, it will be #defined later
165 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000166#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000167/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000168#define debug_printf_parse(...) do {} while (0)
169#define debug_print_tree(a, b) do {} while (0)
170#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000171#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000172#define debug_printf_jobs(...) do {} while (0)
173#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200174#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000175#define debug_printf_glob(...) do {} while (0)
176#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000177#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000178#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000179
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000180#define ERR_PTR ((void*)(long)1)
181
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000182#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000183
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000184#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000185
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200186struct variable;
187
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000188static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
189
190/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000191 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000192 */
193#if !BB_MMU
194typedef struct nommu_save_t {
195 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200196 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000197 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000198 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000199} nommu_save_t;
200#endif
201
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000202typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000203 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000204#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000205 RES_IF ,
206 RES_THEN ,
207 RES_ELIF ,
208 RES_ELSE ,
209 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000210#endif
211#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000212 RES_FOR ,
213 RES_WHILE ,
214 RES_UNTIL ,
215 RES_DO ,
216 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000217#endif
218#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000219 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000220#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000221#if ENABLE_HUSH_CASE
222 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200223 /* three pseudo-keywords support contrived "case" syntax: */
224 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
225 RES_MATCH , /* "word)" */
226 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000227 RES_ESAC ,
228#endif
229 RES_XXXX ,
230 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000231} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000232
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000233typedef struct o_string {
234 char *data;
235 int length; /* position where data is appended */
236 int maxlen;
237 /* Protect newly added chars against globbing
238 * (by prepending \ to *, ?, [, \) */
239 smallint o_escape;
240 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000241 /* At least some part of the string was inside '' or "",
242 * possibly empty one: word"", wo''rd etc. */
243 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000244 smallint has_empty_slot;
245 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
246} o_string;
247enum {
248 MAYBE_ASSIGNMENT = 0,
249 DEFINITELY_ASSIGNMENT = 1,
250 NOT_ASSIGNMENT = 2,
251 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
252};
253/* Used for initialization: o_string foo = NULL_O_STRING; */
254#define NULL_O_STRING { NULL }
255
256/* I can almost use ordinary FILE*. Is open_memstream() universally
257 * available? Where is it documented? */
258typedef struct in_str {
259 const char *p;
260 /* eof_flag=1: last char in ->p is really an EOF */
261 char eof_flag; /* meaningless if ->p == NULL */
262 char peek_buf[2];
263#if ENABLE_HUSH_INTERACTIVE
264 smallint promptme;
265 smallint promptmode; /* 0: PS1, 1: PS2 */
266#endif
267 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200268 int (*get) (struct in_str *) FAST_FUNC;
269 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000270} in_str;
271#define i_getch(input) ((input)->get(input))
272#define i_peek(input) ((input)->peek(input))
273
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200274/* The descrip member of this structure is only used to make
275 * debugging output pretty */
276static const struct {
277 int mode;
278 signed char default_fd;
279 char descrip[3];
280} redir_table[] = {
281 { O_RDONLY, 0, "<" },
282 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
283 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
284 { O_CREAT|O_RDWR, 1, "<>" },
285 { O_RDONLY, 0, "<<" },
286/* Should not be needed. Bogus default_fd helps in debugging */
287/* { O_RDONLY, 77, "<<" }, */
288};
289
Eric Andersen25f27032001-04-26 23:22:31 +0000290struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000291 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000292 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000293 int rd_fd; /* fd to redirect */
294 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
295 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000296 smallint rd_type; /* (enum redir_type) */
297 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000298 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200299 * bit 0: do we need to trim leading tabs?
300 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000301 */
Eric Andersen25f27032001-04-26 23:22:31 +0000302};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000303typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200304 REDIRECT_INPUT = 0,
305 REDIRECT_OVERWRITE = 1,
306 REDIRECT_APPEND = 2,
307 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000308 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200309 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000310
311 REDIRFD_CLOSE = -3,
312 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000313 REDIRFD_TO_FILE = -1,
314 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000315
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000316 HEREDOC_SKIPTABS = 1,
317 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000318} redir_type;
319
Eric Andersen25f27032001-04-26 23:22:31 +0000320
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000321struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000322 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000323 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000324 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200325 smallint cmd_type; /* CMD_xxx */
326#define CMD_NORMAL 0
327#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200328
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200329/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200330#if ENABLE_HUSH_BASH_COMPAT
331# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000332#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200333
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200334/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200335//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200336// It is hard to implement correctly, it adds significant amounts of tricky code,
337// and all this is only useful for really obscure export statements
338// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
339// guards the code which implements it, but I have doubts it works
340// in all cases (especially with mixed globbed/non-globbed arguments)
341
342#if ENABLE_HUSH_FUNCTIONS
343# define CMD_FUNCDEF 3
344#endif
345
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200346 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
347 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000348#if !BB_MMU
349 char *group_as_string;
350#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000351#if ENABLE_HUSH_FUNCTIONS
352 struct function *child_func;
353/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200354 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000355 * When we execute "f1() {a;}" cmd, we create new function and clear
356 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200357 * When we execute "f1() {b;}", we notice that f1 exists,
358 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000359 * we put those fields back into cmd->xxx
360 * (struct function has ->parent_cmd ptr to facilitate that).
361 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
362 * Without this trick, loop would execute a;b;b;b;...
363 * instead of correct sequence a;b;a;b;...
364 * When command is freed, it severs the link
365 * (sets ->child_func->parent_cmd to NULL).
366 */
367#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000368 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000369/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
370 * and on execution these are substituted with their values.
371 * Substitution can make _several_ words out of one argv[n]!
372 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000373 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000374 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000375 struct redir_struct *redirects; /* I/O redirections */
376};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000377/* Is there anything in this command at all? */
378#define IS_NULL_CMD(cmd) \
379 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
380
Eric Andersen25f27032001-04-26 23:22:31 +0000381
382struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000383 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000384 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000385 int alive_cmds; /* number of commands running (not exited) */
386 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000387#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000388 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000389 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000390 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000391#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000392 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000393 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000394 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
395 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000396};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000397typedef enum pipe_style {
398 PIPE_SEQ = 1,
399 PIPE_AND = 2,
400 PIPE_OR = 3,
401 PIPE_BG = 4,
402} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000403/* Is there anything in this pipe at all? */
404#define IS_NULL_PIPE(pi) \
405 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000406
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000407/* This holds pointers to the various results of parsing */
408struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000409 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000410 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000411 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000412 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000413 /* last command in pipe (being constructed right now) */
414 struct command *command;
415 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000416 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000417#if !BB_MMU
418 o_string as_string;
419#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000420#if HAS_KEYWORDS
421 smallint ctx_res_w;
422 smallint ctx_inverted; /* "! cmd | cmd" */
423#if ENABLE_HUSH_CASE
424 smallint ctx_dsemicolon; /* ";;" seen */
425#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000426 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
427 int old_flag;
428 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000429 * example: "if pipe1; pipe2; then pipe3; fi"
430 * when we see "if" or "then", we malloc and copy current context,
431 * and make ->stack point to it. then we parse pipeN.
432 * when closing "then" / fi" / whatever is found,
433 * we move list_head into ->stack->command->group,
434 * copy ->stack into current context, and delete ->stack.
435 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000436 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000437 struct parse_context *stack;
438#endif
439};
440
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000441/* On program start, environ points to initial environment.
442 * putenv adds new pointers into it, unsetenv removes them.
443 * Neither of these (de)allocates the strings.
444 * setenv allocates new strings in malloc space and does putenv,
445 * and thus setenv is unusable (leaky) for shell's purposes */
446#define setenv(...) setenv_is_leaky_dont_use()
447struct variable {
448 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000449 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200450#if ENABLE_HUSH_LOCAL
451 unsigned func_nest_level;
452#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000453 int max_len; /* if > 0, name is part of initial env; else name is malloced */
454 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000455 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000456};
457
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000458enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000459 BC_BREAK = 1,
460 BC_CONTINUE = 2,
461};
462
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000463#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000464struct function {
465 struct function *next;
466 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000467 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000468 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200469# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000470 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200471# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000472};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000473#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000474
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000475
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000476/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000477/* Sorted roughly by size (smaller offsets == smaller code) */
478struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000479 /* interactive_fd != 0 means we are an interactive shell.
480 * If we are, then saved_tty_pgrp can also be != 0, meaning
481 * that controlling tty is available. With saved_tty_pgrp == 0,
482 * job control still works, but terminal signals
483 * (^C, ^Z, ^Y, ^\) won't work at all, and background
484 * process groups can only be created with "cmd &".
485 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
486 * to give tty to the foreground process group,
487 * and will take it back when the group is stopped (^Z)
488 * or killed (^C).
489 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000490#if ENABLE_HUSH_INTERACTIVE
491 /* 'interactive_fd' is a fd# open to ctty, if we have one
492 * _AND_ if we decided to act interactively */
493 int interactive_fd;
494 const char *PS1;
495 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000496# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000497#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000498# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000499#endif
500#if ENABLE_FEATURE_EDITING
501 line_input_t *line_input_state;
502#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000503 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200504 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000505 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200506#if ENABLE_HUSH_RANDOM_SUPPORT
507 random_t random_gen;
508#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000509#if ENABLE_HUSH_JOB
510 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000511 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000512 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000513 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400514# define G_saved_tty_pgrp (G.saved_tty_pgrp)
515#else
516# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000517#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000518 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000519#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000520 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000521#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000522#if ENABLE_HUSH_FUNCTIONS
523 /* 0: outside of a function (or sourced file)
524 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000525 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000526 */
527 smallint flag_return_in_progress;
528#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000529 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000530 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000531 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000532 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000533 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000534 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100535 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000536 /* how many non-NULL argv's we have. NB: $# + 1 */
537 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000538 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000539#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000540 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000541#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000542#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000543 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000544 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000545#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000546 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000547 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000548 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000549 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000550#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000551 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200552# if ENABLE_HUSH_LOCAL
553 struct variable **shadowed_vars_pp;
554 unsigned func_nest_level;
555# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000556#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000557 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200558#if ENABLE_HUSH_FAST
559 unsigned count_SIGCHLD;
560 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200561 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200562#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000563 /* which signals have non-DFL handler (even with no traps set)? */
564 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000565 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000566 sigset_t blocked_set;
567 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000568#if HUSH_DEBUG
569 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000570 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000571#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200572 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000573};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000574#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000575/* Not #defining name to G.name - this quickly gets unwieldy
576 * (too many defines). Also, I actually prefer to see when a variable
577 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000578#define INIT_G() do { \
579 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
580} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000581
582
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000583/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200584static int builtin_cd(char **argv) FAST_FUNC;
585static int builtin_echo(char **argv) FAST_FUNC;
586static int builtin_eval(char **argv) FAST_FUNC;
587static int builtin_exec(char **argv) FAST_FUNC;
588static int builtin_exit(char **argv) FAST_FUNC;
589static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000590#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200591static int builtin_fg_bg(char **argv) FAST_FUNC;
592static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000593#endif
594#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200595static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000596#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200597#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200598static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200599#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000600#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200601static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000602#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400603#if ENABLE_PRINTF
604static int builtin_printf(char **argv) FAST_FUNC;
605#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200606static int builtin_pwd(char **argv) FAST_FUNC;
607static int builtin_read(char **argv) FAST_FUNC;
608static int builtin_set(char **argv) FAST_FUNC;
609static int builtin_shift(char **argv) FAST_FUNC;
610static int builtin_source(char **argv) FAST_FUNC;
611static int builtin_test(char **argv) FAST_FUNC;
612static int builtin_trap(char **argv) FAST_FUNC;
613static int builtin_type(char **argv) FAST_FUNC;
614static int builtin_true(char **argv) FAST_FUNC;
615static int builtin_umask(char **argv) FAST_FUNC;
616static int builtin_unset(char **argv) FAST_FUNC;
617static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000618#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200619static int builtin_break(char **argv) FAST_FUNC;
620static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000621#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000622#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200623static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000624#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000625
626/* Table of built-in functions. They can be forked or not, depending on
627 * context: within pipes, they fork. As simple commands, they do not.
628 * When used in non-forking context, they can change global variables
629 * in the parent shell process. If forked, of course they cannot.
630 * For example, 'unset foo | whatever' will parse and run, but foo will
631 * still be set at the end. */
632struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100633 const char *b_cmd;
634 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000635#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100636 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200637# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000638#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200639# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000640#endif
641};
642
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200643static const struct built_in_command bltins1[] = {
644 BLTIN("." , builtin_source , "Run commands in a file"),
645 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000646#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200647 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000648#endif
649#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200650 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000651#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200652 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000653#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200654 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000655#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200656 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
657 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
658 BLTIN("exit" , builtin_exit , "Exit"),
659 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000660#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200661 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000662#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000663#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200664 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000665#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000666#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200667 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000668#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200669#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200670 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200671#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000672#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200673 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000674#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200675 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000676#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200677 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000678#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200679 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
680 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200681#if ENABLE_HUSH_BASH_COMPAT
682 BLTIN("source" , builtin_source , "Run commands in a file"),
683#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200684 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100685 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100686 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200687 BLTIN("umask" , builtin_umask , "Set file creation mask"),
688 BLTIN("unset" , builtin_unset , "Unset variables"),
689 BLTIN("wait" , builtin_wait , "Wait for process"),
690};
691/* For now, echo and test are unconditionally enabled.
692 * Maybe make it configurable? */
693static const struct built_in_command bltins2[] = {
694 BLTIN("[" , builtin_test , NULL),
695 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400696#if ENABLE_PRINTF
697 BLTIN("printf" , builtin_printf , NULL),
698#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200699 BLTIN("pwd" , builtin_pwd , NULL),
700 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000701};
702
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000703
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000704/* Debug printouts.
705 */
706#if HUSH_DEBUG
707/* prevent disasters with G.debug_indent < 0 */
708# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
709# define debug_enter() (G.debug_indent++)
710# define debug_leave() (G.debug_indent--)
711#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200712# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000713# define debug_enter() ((void)0)
714# define debug_leave() ((void)0)
715#endif
716
717#ifndef debug_printf
718# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
719#endif
720
721#ifndef debug_printf_parse
722# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
723#endif
724
725#ifndef debug_printf_exec
726#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
727#endif
728
729#ifndef debug_printf_env
730# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
731#endif
732
733#ifndef debug_printf_jobs
734# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
735# define DEBUG_JOBS 1
736#else
737# define DEBUG_JOBS 0
738#endif
739
740#ifndef debug_printf_expand
741# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
742# define DEBUG_EXPAND 1
743#else
744# define DEBUG_EXPAND 0
745#endif
746
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200747#ifndef debug_printf_varexp
748# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
749#endif
750
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000751#ifndef debug_printf_glob
752# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
753# define DEBUG_GLOB 1
754#else
755# define DEBUG_GLOB 0
756#endif
757
758#ifndef debug_printf_list
759# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
760#endif
761
762#ifndef debug_printf_subst
763# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
764#endif
765
766#ifndef debug_printf_clean
767# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
768# define DEBUG_CLEAN 1
769#else
770# define DEBUG_CLEAN 0
771#endif
772
773#if DEBUG_EXPAND
774static void debug_print_strings(const char *prefix, char **vv)
775{
776 indent();
777 fprintf(stderr, "%s:\n", prefix);
778 while (*vv)
779 fprintf(stderr, " '%s'\n", *vv++);
780}
781#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200782# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000783#endif
784
785
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000786/* Leak hunting. Use hush_leaktool.sh for post-processing.
787 */
788#if LEAK_HUNTING
789static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000790{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000791 void *ptr = xmalloc((size + 0xff) & ~0xff);
792 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
793 return ptr;
794}
795static void *xxrealloc(int lineno, void *ptr, size_t size)
796{
797 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
798 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
799 return ptr;
800}
801static char *xxstrdup(int lineno, const char *str)
802{
803 char *ptr = xstrdup(str);
804 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
805 return ptr;
806}
807static void xxfree(void *ptr)
808{
809 fdprintf(2, "free %p\n", ptr);
810 free(ptr);
811}
812#define xmalloc(s) xxmalloc(__LINE__, s)
813#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
814#define xstrdup(s) xxstrdup(__LINE__, s)
815#define free(p) xxfree(p)
816#endif
817
818
819/* Syntax and runtime errors. They always abort scripts.
820 * In interactive use they usually discard unparsed and/or unexecuted commands
821 * and return to the prompt.
822 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
823 */
824#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200825# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000826# define syntax_error(lineno, msg) syntax_error(msg)
827# define syntax_error_at(lineno, msg) syntax_error_at(msg)
828# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
829# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
830# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000831#endif
832
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000833static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000834{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000835 va_list p;
836
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000837#if HUSH_DEBUG >= 2
838 bb_error_msg("hush.c:%u", lineno);
839#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000840 va_start(p, fmt);
841 bb_verror_msg(fmt, p, NULL);
842 va_end(p);
843 if (!G_interactive_fd)
844 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000845}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000846
847static void syntax_error(unsigned lineno, const char *msg)
848{
849 if (msg)
850 die_if_script(lineno, "syntax error: %s", msg);
851 else
852 die_if_script(lineno, "syntax error", NULL);
853}
854
855static void syntax_error_at(unsigned lineno, const char *msg)
856{
857 die_if_script(lineno, "syntax error at '%s'", msg);
858}
859
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400860static void syntax_error_unterm_str(unsigned lineno, const char *s)
861{
862 die_if_script(lineno, "syntax error: unterminated %s", s);
863}
864
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000865/* It so happens that all such cases are totally fatal
866 * even if shell is interactive: EOF while looking for closing
867 * delimiter. There is nowhere to read stuff from after that,
868 * it's EOF! The only choice is to terminate.
869 */
870static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000871static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000872{
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400873 char msg[2] = { ch, '\0' };
874 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000875 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000876}
877
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200878static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000879{
880 char msg[2];
881 msg[0] = ch;
882 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200883 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000884}
885
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000886#if HUSH_DEBUG < 2
887# undef die_if_script
888# undef syntax_error
889# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000890# undef syntax_error_unterm_ch
891# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000892# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000893#else
Denys Vlasenko606291b2009-09-23 23:15:43 +0200894# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000895# define syntax_error(msg) syntax_error(__LINE__, msg)
896# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
897# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
898# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
899# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000900#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000901
Denis Vlasenko552433b2009-04-04 19:29:21 +0000902
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000903#if ENABLE_HUSH_INTERACTIVE
904static void cmdedit_update_prompt(void);
905#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200906# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000907#endif
908
909
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000910/* Utility functions
911 */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000912/* Replace each \x with x in place, return ptr past NUL. */
913static char *unbackslash(char *src)
914{
Denys Vlasenko71885402009-09-24 01:44:13 +0200915 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +0000916 while (1) {
917 if (*src == '\\')
918 src++;
919 if ((*dst++ = *src++) == '\0')
920 break;
921 }
922 return dst;
923}
924
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000925static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000926{
927 int i;
928 unsigned count1;
929 unsigned count2;
930 char **v;
931
932 v = strings;
933 count1 = 0;
934 if (v) {
935 while (*v) {
936 count1++;
937 v++;
938 }
939 }
940 count2 = 0;
941 v = add;
942 while (*v) {
943 count2++;
944 v++;
945 }
946 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
947 v[count1 + count2] = NULL;
948 i = count2;
949 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000950 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000951 return v;
952}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000953#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000954static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
955{
956 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
957 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
958 return ptr;
959}
960#define add_strings_to_strings(strings, add, need_to_dup) \
961 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
962#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000963
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200964/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000965static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000966{
967 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000968 v[0] = add;
969 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000970 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000971}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000972#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000973static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
974{
975 char **ptr = add_string_to_strings(strings, add);
976 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
977 return ptr;
978}
979#define add_string_to_strings(strings, add) \
980 xx_add_string_to_strings(__LINE__, strings, add)
981#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000982
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200983static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000984{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000985 char **v;
986
987 if (!strings)
988 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000989 v = strings;
990 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200991 free(*v);
992 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000993 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000994 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000995}
996
Denis Vlasenko76d50412008-06-10 16:19:39 +0000997
Denis Vlasenko270b1c32009-04-17 18:54:50 +0000998/* Helpers for setting new $n and restoring them back
999 */
1000typedef struct save_arg_t {
1001 char *sv_argv0;
1002 char **sv_g_argv;
1003 int sv_g_argc;
1004 smallint sv_g_malloced;
1005} save_arg_t;
1006
1007static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1008{
1009 int n;
1010
1011 sv->sv_argv0 = argv[0];
1012 sv->sv_g_argv = G.global_argv;
1013 sv->sv_g_argc = G.global_argc;
1014 sv->sv_g_malloced = G.global_args_malloced;
1015
1016 argv[0] = G.global_argv[0]; /* retain $0 */
1017 G.global_argv = argv;
1018 G.global_args_malloced = 0;
1019
1020 n = 1;
1021 while (*++argv)
1022 n++;
1023 G.global_argc = n;
1024}
1025
1026static void restore_G_args(save_arg_t *sv, char **argv)
1027{
1028 char **pp;
1029
1030 if (G.global_args_malloced) {
1031 /* someone ran "set -- arg1 arg2 ...", undo */
1032 pp = G.global_argv;
1033 while (*++pp) /* note: does not free $0 */
1034 free(*pp);
1035 free(G.global_argv);
1036 }
1037 argv[0] = sv->sv_argv0;
1038 G.global_argv = sv->sv_g_argv;
1039 G.global_argc = sv->sv_g_argc;
1040 G.global_args_malloced = sv->sv_g_malloced;
1041}
1042
1043
Denis Vlasenkod5762932009-03-31 11:22:57 +00001044/* Basic theory of signal handling in shell
1045 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001046 * This does not describe what hush does, rather, it is current understanding
1047 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001048 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1049 *
1050 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1051 * is finished or backgrounded. It is the same in interactive and
1052 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001053 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001054 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001055 * backgrounds (i.e. stops) or kills all members of currently running
1056 * pipe.
1057 *
1058 * Wait builtin in interruptible by signals for which user trap is set
1059 * or by SIGINT in interactive shell.
1060 *
1061 * Trap handlers will execute even within trap handlers. (right?)
1062 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001063 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1064 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001065 *
1066 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001067 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001068 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001069 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001070 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001071 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001072 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001073 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001074 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001075 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001076 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001077 *
1078 * SIGQUIT: ignore
1079 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001080 * SIGHUP (interactive):
1081 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001082 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001083 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1084 * that all pipe members are stopped. Try this in bash:
1085 * while :; do :; done - ^Z does not background it
1086 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001087 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001088 * of the command line, show prompt. NB: ^C does not send SIGINT
1089 * to interactive shell while shell is waiting for a pipe,
1090 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001091 * Example 1: this waits 5 sec, but does not execute ls:
1092 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1093 * Example 2: this does not wait and does not execute ls:
1094 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1095 * Example 3: this does not wait 5 sec, but executes ls:
1096 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001097 *
1098 * (What happens to signals which are IGN on shell start?)
1099 * (What happens with signal mask on shell start?)
1100 *
1101 * Implementation in hush
1102 * ======================
1103 * We use in-kernel pending signal mask to determine which signals were sent.
1104 * We block all signals which we don't want to take action immediately,
1105 * i.e. we block all signals which need to have special handling as described
1106 * above, and all signals which have traps set.
1107 * After each pipe execution, we extract any pending signals via sigtimedwait()
1108 * and act on them.
1109 *
1110 * unsigned non_DFL_mask: a mask of such "special" signals
1111 * sigset_t blocked_set: current blocked signal set
1112 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001113 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001114 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001115 * "trap 'cmd' SIGxxx":
1116 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001117 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001118 * unblock signals with special interactive handling
1119 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001120 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001121 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001122 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001123 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001124 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001125 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001126 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001127 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001128 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001129 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001130 * Standard says "When a subshell is entered, traps that are not being ignored
1131 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001132 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001133 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001134enum {
1135 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001136 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001137 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001138 | (1 << SIGHUP)
1139 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001140 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001141#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001142 | (1 << SIGTTIN)
1143 | (1 << SIGTTOU)
1144 | (1 << SIGTSTP)
1145#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001146};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001147
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001148#if ENABLE_HUSH_FAST
1149static void SIGCHLD_handler(int sig UNUSED_PARAM)
1150{
1151 G.count_SIGCHLD++;
1152//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1153}
1154#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001155
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001156#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001157
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001158/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1159#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001160/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001161#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1162
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001163/* Restores tty foreground process group, and exits.
1164 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001165 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001166 * or called directly with -EXITCODE.
1167 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001168static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001169static void sigexit(int sig)
1170{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001171 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001172 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001173
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001174 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001175 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001176 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1177 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001178
1179 /* Not a signal, just exit */
1180 if (sig <= 0)
1181 _exit(- sig);
1182
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001183 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001184}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001185#else
1186
1187#define disable_restore_tty_pgrp_on_exit() ((void)0)
1188#define enable_restore_tty_pgrp_on_exit() ((void)0)
1189
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001190#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001191
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001192/* Restores tty foreground process group, and exits. */
1193static void hush_exit(int exitcode) NORETURN;
1194static void hush_exit(int exitcode)
1195{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001196 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1197 /* Prevent recursion:
1198 * trap "echo Hi; exit" EXIT; exit
1199 */
1200 char *argv[] = { NULL, G.traps[0], NULL };
1201 G.traps[0] = NULL;
1202 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001203 builtin_eval(argv);
1204 free(argv[1]);
1205 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001206
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001207#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001208 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001209 sigexit(- (exitcode & 0xff));
1210#else
1211 exit(exitcode);
1212#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001213}
1214
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001215static int check_and_run_traps(int sig)
1216{
1217 static const struct timespec zero_timespec = { 0, 0 };
1218 smalluint save_rcode;
1219 int last_sig = 0;
1220
1221 if (sig)
1222 goto jump_in;
1223 while (1) {
1224 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1225 if (sig <= 0)
1226 break;
1227 jump_in:
1228 last_sig = sig;
1229 if (G.traps && G.traps[sig]) {
1230 if (G.traps[sig][0]) {
1231 /* We have user-defined handler */
1232 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1233 save_rcode = G.last_exitcode;
1234 builtin_eval(argv);
1235 free(argv[1]);
1236 G.last_exitcode = save_rcode;
1237 } /* else: "" trap, ignoring signal */
1238 continue;
1239 }
1240 /* not a trap: special action */
1241 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001242#if ENABLE_HUSH_FAST
1243 case SIGCHLD:
1244 G.count_SIGCHLD++;
1245//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1246 break;
1247#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001248 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001249 /* Builtin was ^C'ed, make it look prettier: */
1250 bb_putchar('\n');
1251 G.flag_SIGINT = 1;
1252 break;
1253#if ENABLE_HUSH_JOB
1254 case SIGHUP: {
1255 struct pipe *job;
1256 /* bash is observed to signal whole process groups,
1257 * not individual processes */
1258 for (job = G.job_list; job; job = job->next) {
1259 if (job->pgrp <= 0)
1260 continue;
1261 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1262 if (kill(- job->pgrp, SIGHUP) == 0)
1263 kill(- job->pgrp, SIGCONT);
1264 }
1265 sigexit(SIGHUP);
1266 }
1267#endif
1268 default: /* ignored: */
1269 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1270 break;
1271 }
1272 }
1273 return last_sig;
1274}
1275
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001276
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001277static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001278{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001279 if (force || G.cwd == NULL) {
1280 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1281 * we must not try to free(bb_msg_unknown) */
1282 if (G.cwd == bb_msg_unknown)
1283 G.cwd = NULL;
1284 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1285 if (!G.cwd)
1286 G.cwd = bb_msg_unknown;
1287 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001288 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001289}
1290
Denis Vlasenko83506862007-11-23 13:11:42 +00001291
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001292/*
1293 * Shell and environment variable support
1294 */
1295static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001296{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001297 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001298 struct variable *cur;
1299 int len;
1300
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001301 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001302 pp = &G.top_var;
1303 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001304 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001305 return pp;
1306 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001307 }
1308 return NULL;
1309}
1310
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001311static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001312{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001313 struct variable **pp = get_ptr_to_local_var(name);
1314 if (pp)
1315 return *pp;
1316 return NULL;
1317}
1318
Denys Vlasenko03dad222010-01-12 23:29:57 +01001319static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001320{
1321 struct variable **pp = get_ptr_to_local_var(name);
1322 if (pp)
1323 return strchr((*pp)->varstr, '=') + 1;
Denys Vlasenkodea47882009-10-09 15:40:49 +02001324 if (strcmp(name, "PPID") == 0)
1325 return utoa(G.root_ppid);
1326 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001327#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001328 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001329 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001330 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001331#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001332 return NULL;
1333}
1334
1335/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001336 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001337 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001338 * 0: do not change export flag
1339 * (if creating new variable, flag will be 0)
1340 * 1: set export flag and putenv the variable
1341 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001342 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001343 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001344#if !BB_MMU && ENABLE_HUSH_LOCAL
1345/* all params are used */
1346#elif BB_MMU && ENABLE_HUSH_LOCAL
1347#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1348 set_local_var(str, flg_export, local_lvl)
1349#elif BB_MMU && !ENABLE_HUSH_LOCAL
1350#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001351 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001352#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1353#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1354 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001355#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001356static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001357{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001358 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001359 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001360 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001361 int name_len;
1362
Denis Vlasenko950bd722009-04-21 11:23:56 +00001363 eq_sign = strchr(str, '=');
1364 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001365 free(str);
1366 return -1;
1367 }
1368
Denis Vlasenko950bd722009-04-21 11:23:56 +00001369 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001370 var_pp = &G.top_var;
1371 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001372 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001373 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001374 continue;
1375 }
1376 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001377 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001378#if !BB_MMU
1379 if (!flg_read_only)
1380#endif
1381 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001382 free(str);
1383 return -1;
1384 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001385 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001386 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1387 *eq_sign = '\0';
1388 unsetenv(str);
1389 *eq_sign = '=';
1390 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001391#if ENABLE_HUSH_LOCAL
1392 if (cur->func_nest_level < local_lvl) {
1393 /* New variable is declared as local,
1394 * and existing one is global, or local
1395 * from enclosing function.
1396 * Remove and save old one: */
1397 *var_pp = cur->next;
1398 cur->next = *G.shadowed_vars_pp;
1399 *G.shadowed_vars_pp = cur;
1400 /* bash 3.2.33(1) and exported vars:
1401 * # export z=z
1402 * # f() { local z=a; env | grep ^z; }
1403 * # f
1404 * z=a
1405 * # env | grep ^z
1406 * z=z
1407 */
1408 if (cur->flg_export)
1409 flg_export = 1;
1410 break;
1411 }
1412#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001413 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001414 free_and_exp:
1415 free(str);
1416 goto exp;
1417 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001418 if (cur->max_len != 0) {
1419 if (cur->max_len >= strlen(str)) {
1420 /* This one is from startup env, reuse space */
1421 strcpy(cur->varstr, str);
1422 goto free_and_exp;
1423 }
1424 } else {
1425 /* max_len == 0 signifies "malloced" var, which we can
1426 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001427 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001428 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001429 cur->max_len = 0;
1430 goto set_str_and_exp;
1431 }
1432
Denys Vlasenko295fef82009-06-03 12:47:26 +02001433 /* Not found - create new variable struct */
1434 cur = xzalloc(sizeof(*cur));
1435#if ENABLE_HUSH_LOCAL
1436 cur->func_nest_level = local_lvl;
1437#endif
1438 cur->next = *var_pp;
1439 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001440
1441 set_str_and_exp:
1442 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001443#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001444 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001445#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001446 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001447 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001448 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001449 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1450 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001451 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001452 if (flg_export == -1) {
1453 cur->flg_export = 0;
1454 /* unsetenv was already done */
1455 } else {
1456 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1457 return putenv(cur->varstr);
1458 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001459 }
1460 return 0;
1461}
1462
Denys Vlasenko6db47842009-09-05 20:15:17 +02001463/* Used at startup and after each cd */
1464static void set_pwd_var(int exp)
1465{
1466 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1467 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1468}
1469
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001470static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001471{
1472 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001473 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001474
1475 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001476 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001477 var_pp = &G.top_var;
1478 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001479 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1480 if (cur->flg_read_only) {
1481 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001482 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001483 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001484 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001485 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1486 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001487 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1488 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001489 if (!cur->max_len)
1490 free(cur->varstr);
1491 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001492 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001493 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001494 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001495 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001496 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001497}
1498
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001499static int unset_local_var(const char *name)
1500{
1501 return unset_local_var_len(name, strlen(name));
1502}
1503
1504static void unset_vars(char **strings)
1505{
1506 char **v;
1507
1508 if (!strings)
1509 return;
1510 v = strings;
1511 while (*v) {
1512 const char *eq = strchrnul(*v, '=');
1513 unset_local_var_len(*v, (int)(eq - *v));
1514 v++;
1515 }
1516 free(strings);
1517}
1518
Mike Frysinger98c52642009-04-02 10:02:37 +00001519#if ENABLE_SH_MATH_SUPPORT
1520#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1521#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denys Vlasenko03dad222010-01-12 23:29:57 +01001522static char* FAST_FUNC endofname(const char *name)
Mike Frysinger98c52642009-04-02 10:02:37 +00001523{
1524 char *p;
1525
1526 p = (char *) name;
1527 if (!is_name(*p))
1528 return p;
1529 while (*++p) {
1530 if (!is_in_name(*p))
1531 break;
1532 }
1533 return p;
1534}
Denys Vlasenko6b01b712010-01-24 22:52:21 +01001535#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001536
Denys Vlasenko03dad222010-01-12 23:29:57 +01001537static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001538{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001539 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001540 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001541}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001542
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001543
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001544/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001545 * Helpers for "var1=val1 var2=val2 cmd" feature
1546 */
1547static void add_vars(struct variable *var)
1548{
1549 struct variable *next;
1550
1551 while (var) {
1552 next = var->next;
1553 var->next = G.top_var;
1554 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001555 if (var->flg_export) {
1556 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001557 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001558 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001559 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001560 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001561 var = next;
1562 }
1563}
1564
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001565static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001566{
1567 char **s;
1568 struct variable *old = NULL;
1569
1570 if (!strings)
1571 return old;
1572 s = strings;
1573 while (*s) {
1574 struct variable *var_p;
1575 struct variable **var_pp;
1576 char *eq;
1577
1578 eq = strchr(*s, '=');
1579 if (eq) {
1580 *eq = '\0';
1581 var_pp = get_ptr_to_local_var(*s);
1582 *eq = '=';
1583 if (var_pp) {
1584 /* Remove variable from global linked list */
1585 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001586 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001587 *var_pp = var_p->next;
1588 /* Add it to returned list */
1589 var_p->next = old;
1590 old = var_p;
1591 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001592 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001593 }
1594 s++;
1595 }
1596 return old;
1597}
1598
1599
1600/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001601 * in_str support
1602 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001603static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001604{
1605 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001606 if (ch != '\0')
1607 return ch;
1608 i->p--;
1609 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001610}
1611
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001612static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001613{
1614 return *i->p;
1615}
1616
1617#if ENABLE_HUSH_INTERACTIVE
1618
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001619static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001620{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001621 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001622 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001623 if (G.PS1 == NULL)
1624 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001625 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001626 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001627 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001628 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001629 if (G.PS2 == NULL)
1630 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001631}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001632
1633static const char* setup_prompt_string(int promptmode)
1634{
1635 const char *prompt_str;
1636 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001637 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1638 /* Set up the prompt */
1639 if (promptmode == 0) { /* PS1 */
1640 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001641 /* bash uses $PWD value, even if it is set by user.
1642 * It uses current dir only if PWD is unset.
1643 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001644 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001645 prompt_str = G.PS1;
1646 } else
1647 prompt_str = G.PS2;
1648 } else
1649 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001650 debug_printf("result '%s'\n", prompt_str);
1651 return prompt_str;
1652}
1653
1654static void get_user_input(struct in_str *i)
1655{
1656 int r;
1657 const char *prompt_str;
1658
1659 prompt_str = setup_prompt_string(i->promptmode);
1660#if ENABLE_FEATURE_EDITING
1661 /* Enable command line editing only while a command line
1662 * is actually being read */
1663 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001664 G.flag_SIGINT = 0;
1665 /* buglet: SIGINT will not make new prompt to appear _at once_,
1666 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001667 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 +00001668 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001669 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001670 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001671 i->eof_flag = (r < 0);
1672 if (i->eof_flag) { /* EOF/error detected */
1673 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1674 G.user_input_buf[1] = '\0';
1675 }
1676#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001677 do {
1678 G.flag_SIGINT = 0;
1679 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001680 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001681 G.user_input_buf[0] = r = fgetc(i->file);
1682 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001683//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001684 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001685 i->eof_flag = (r == EOF);
1686#endif
1687 i->p = G.user_input_buf;
1688}
1689
1690#endif /* INTERACTIVE */
1691
1692/* This is the magic location that prints prompts
1693 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001694static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001695{
1696 int ch;
1697
1698 /* If there is data waiting, eat it up */
1699 if (i->p && *i->p) {
1700#if ENABLE_HUSH_INTERACTIVE
1701 take_cached:
1702#endif
1703 ch = *i->p++;
1704 if (i->eof_flag && !*i->p)
1705 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001706 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001707 } else {
1708 /* need to double check i->file because we might be doing something
1709 * more complicated by now, like sourcing or substituting. */
1710#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001711 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001712 do {
1713 get_user_input(i);
1714 } while (!*i->p); /* need non-empty line */
1715 i->promptmode = 1; /* PS2 */
1716 i->promptme = 0;
1717 goto take_cached;
1718 }
1719#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001720 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001721 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001722 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001723#if ENABLE_HUSH_INTERACTIVE
1724 if (ch == '\n')
1725 i->promptme = 1;
1726#endif
1727 return ch;
1728}
1729
Denis Vlasenko913a2012009-04-05 22:17:04 +00001730/* All callers guarantee this routine will never
1731 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001732 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001733static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001734{
1735 int ch;
1736 if (i->p && *i->p) {
1737 if (i->eof_flag && !i->p[1])
1738 return EOF;
1739 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001740 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001741 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001742 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001743 i->eof_flag = (ch == EOF);
1744 i->peek_buf[0] = ch;
1745 i->peek_buf[1] = '\0';
1746 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001747 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001748 return ch;
1749}
1750
1751static void setup_file_in_str(struct in_str *i, FILE *f)
1752{
1753 i->peek = file_peek;
1754 i->get = file_get;
1755#if ENABLE_HUSH_INTERACTIVE
1756 i->promptme = 1;
1757 i->promptmode = 0; /* PS1 */
1758#endif
1759 i->file = f;
1760 i->p = NULL;
1761}
1762
1763static void setup_string_in_str(struct in_str *i, const char *s)
1764{
1765 i->peek = static_peek;
1766 i->get = static_get;
1767#if ENABLE_HUSH_INTERACTIVE
1768 i->promptme = 1;
1769 i->promptmode = 0; /* PS1 */
1770#endif
1771 i->p = s;
1772 i->eof_flag = 0;
1773}
1774
1775
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001776/*
1777 * o_string support
1778 */
1779#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001780
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001781static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001782{
1783 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001784 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001785 if (o->data)
1786 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001787}
1788
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001789static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001790{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001791 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001792 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001793}
1794
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001795static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1796{
1797 free(o->data);
1798}
1799
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001800static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001801{
1802 if (o->length + len > o->maxlen) {
1803 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1804 o->data = xrealloc(o->data, 1 + o->maxlen);
1805 }
1806}
1807
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001808static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001809{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001810 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1811 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001812 o->data[o->length] = ch;
1813 o->length++;
1814 o->data[o->length] = '\0';
1815}
1816
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001817static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001818{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001819 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001820 memcpy(&o->data[o->length], str, len);
1821 o->length += len;
1822 o->data[o->length] = '\0';
1823}
1824
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001825static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001826{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001827 o_addblock(o, str, strlen(str));
1828}
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001829#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001830static void nommu_addchr(o_string *o, int ch)
1831{
1832 if (o)
1833 o_addchr(o, ch);
1834}
1835#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001836# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001837#endif
1838
1839static void o_addstr_with_NUL(o_string *o, const char *str)
1840{
1841 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001842}
1843
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001844static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001845{
1846 while (len) {
1847 o_addchr(o, *str);
1848 if (*str++ == '\\'
1849 && (*str != '*' && *str != '?' && *str != '[')
1850 ) {
1851 o_addchr(o, '\\');
1852 }
1853 len--;
1854 }
1855}
1856
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001857#undef HUSH_BRACE_EXP
1858/*
1859 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
1860 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
1861 * Apparently, on unquoted $v bash still does globbing
1862 * ("v='*.txt'; echo $v" prints all .txt files),
1863 * but NOT brace expansion! Thus, there should be TWO independent
1864 * quoting mechanisms on $v expansion side: one protects
1865 * $v from brace expansion, and other additionally protects "$v" against globbing.
1866 * We have only second one.
1867 */
1868
1869#ifdef HUSH_BRACE_EXP
1870# define MAYBE_BRACES "{}"
1871#else
1872# define MAYBE_BRACES ""
1873#endif
1874
Eric Andersen25f27032001-04-26 23:22:31 +00001875/* My analysis of quoting semantics tells me that state information
1876 * is associated with a destination, not a source.
1877 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001878static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001879{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001880 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001881 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001882 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001883 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001884 o_grow_by(o, sz);
1885 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001886 o->data[o->length] = '\\';
1887 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001888 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001889 o->data[o->length] = ch;
1890 o->length++;
1891 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001892}
1893
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001894static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001895{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001896 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001897 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001898 sz++;
1899 o->data[o->length] = '\\';
1900 o->length++;
1901 }
1902 o_grow_by(o, sz);
1903 o->data[o->length] = ch;
1904 o->length++;
1905 o->data[o->length] = '\0';
1906}
1907
1908static void o_addQstr(o_string *o, const char *str, int len)
1909{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001910 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001911 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001912 return;
1913 }
1914 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001915 char ch;
1916 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001917 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001918 if (ordinary_cnt > len) /* paranoia */
1919 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001920 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001921 if (ordinary_cnt == len)
1922 return;
1923 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001924 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001925
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001926 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001927 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001928 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001929 sz++;
1930 o->data[o->length] = '\\';
1931 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001932 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001933 o_grow_by(o, sz);
1934 o->data[o->length] = ch;
1935 o->length++;
1936 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001937 }
1938}
1939
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001940/* A special kind of o_string for $VAR and `cmd` expansion.
1941 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001942 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001943 * list[i] contains an INDEX (int!) into this string data.
1944 * It means that if list[] needs to grow, data needs to be moved higher up
1945 * but list[i]'s need not be modified.
1946 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001947 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001948 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1949 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001950#if DEBUG_EXPAND || DEBUG_GLOB
1951static void debug_print_list(const char *prefix, o_string *o, int n)
1952{
1953 char **list = (char**)o->data;
1954 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1955 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001956
1957 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001958 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1959 prefix, list, n, string_start, o->length, o->maxlen);
1960 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001961 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001962 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1963 o->data + (int)list[i] + string_start,
1964 o->data + (int)list[i] + string_start);
1965 i++;
1966 }
1967 if (n) {
1968 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001969 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001970 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001971 }
1972}
1973#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001974# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001975#endif
1976
1977/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1978 * in list[n] so that it points past last stored byte so far.
1979 * It returns n+1. */
1980static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001981{
1982 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001983 int string_start;
1984 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001985
1986 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001987 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1988 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001989 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001990 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001991 /* list[n] points to string_start, make space for 16 more pointers */
1992 o->maxlen += 0x10 * sizeof(list[0]);
1993 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001994 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001995 memmove(list + n + 0x10, list + n, string_len);
1996 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001997 } else {
1998 debug_printf_list("list[%d]=%d string_start=%d\n",
1999 n, string_len, string_start);
2000 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002001 } else {
2002 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002003 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2004 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002005 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2006 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002007 o->has_empty_slot = 0;
2008 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002009 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002010 return n + 1;
2011}
2012
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002013/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002014static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002015{
2016 char **list = (char**)o->data;
2017 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2018
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002019 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002020}
2021
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002022#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002023/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2024 * first, it processes even {a} (no commas), second,
2025 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002026 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002027 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002028
2029/* Helper */
2030static int glob_needed(const char *s)
2031{
2032 while (*s) {
2033 if (*s == '\\') {
2034 if (!s[1])
2035 return 0;
2036 s += 2;
2037 continue;
2038 }
2039 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2040 return 1;
2041 s++;
2042 }
2043 return 0;
2044}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002045/* Return pointer to next closing brace or to comma */
2046static const char *next_brace_sub(const char *cp)
2047{
2048 unsigned depth = 0;
2049 cp++;
2050 while (*cp != '\0') {
2051 if (*cp == '\\') {
2052 if (*++cp == '\0')
2053 break;
2054 cp++;
2055 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002056 }
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002057 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2058 break;
2059 if (*cp++ == '{') /*}*/
2060 depth++;
2061 }
2062
2063 return *cp != '\0' ? cp : NULL;
2064}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002065/* Recursive brace globber. Note: may garble pattern[]. */
2066static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002067{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002068 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002069 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002070 const char *next;
2071 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002072 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002073 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002074
2075 debug_printf_glob("glob_brace('%s')\n", pattern);
2076
2077 begin = pattern;
2078 while (1) {
2079 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002080 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002081 if (*begin == '{') /*}*/ {
2082 /* Find the first sub-pattern and at the same time
2083 * find the rest after the closing brace */
2084 next = next_brace_sub(begin);
2085 if (next == NULL) {
2086 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002087 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002088 }
2089 /*{*/ if (*next == '}') {
2090 /* "{abc}" with no commas - illegal
2091 * brace expr, disregard and skip it */
2092 begin = next + 1;
2093 continue;
2094 }
2095 break;
2096 }
2097 if (*begin == '\\' && begin[1] != '\0')
2098 begin++;
2099 begin++;
2100 }
2101 debug_printf_glob("begin:%s\n", begin);
2102 debug_printf_glob("next:%s\n", next);
2103
2104 /* Now find the end of the whole brace expression */
2105 rest = next;
2106 /*{*/ while (*rest != '}') {
2107 rest = next_brace_sub(rest);
2108 if (rest == NULL) {
2109 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002110 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002111 }
2112 debug_printf_glob("rest:%s\n", rest);
2113 }
2114 rest_len = strlen(++rest) + 1;
2115
2116 /* We are sure the brace expression is well-formed */
2117
2118 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002119 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002120
2121 /* We have a brace expression. BEGIN points to the opening {,
2122 * NEXT points past the terminator of the first element, and REST
2123 * points past the final }. We will accumulate result names from
2124 * recursive runs for each brace alternative in the buffer using
2125 * GLOB_APPEND. */
2126
2127 p = begin + 1;
2128 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002129 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002130 memcpy(
2131 mempcpy(
2132 mempcpy(new_pattern_buf,
2133 /* We know the prefix for all sub-patterns */
2134 pattern, begin - pattern),
2135 p, next - p),
2136 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002137
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002138 /* Note: glob_brace() may garble new_pattern_buf[].
2139 * That's why we re-copy prefix every time (1st memcpy above).
2140 */
2141 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002142 /*{*/ if (*next == '}') {
2143 /* We saw the last entry */
2144 break;
2145 }
2146 p = next + 1;
2147 next = next_brace_sub(next);
2148 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002149 free(new_pattern_buf);
2150 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002151
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002152 simple_glob:
2153 {
2154 int gr;
2155 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002156
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002157 memset(&globdata, 0, sizeof(globdata));
2158 gr = glob(pattern, 0, NULL, &globdata);
2159 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2160 if (gr != 0) {
2161 if (gr == GLOB_NOMATCH) {
2162 globfree(&globdata);
2163 /* NB: garbles parameter */
2164 unbackslash(pattern);
2165 o_addstr_with_NUL(o, pattern);
2166 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2167 return o_save_ptr_helper(o, n);
2168 }
2169 if (gr == GLOB_NOSPACE)
2170 bb_error_msg_and_die(bb_msg_memory_exhausted);
2171 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2172 * but we didn't specify it. Paranoia again. */
2173 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2174 }
2175 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2176 char **argv = globdata.gl_pathv;
2177 while (1) {
2178 o_addstr_with_NUL(o, *argv);
2179 n = o_save_ptr_helper(o, n);
2180 argv++;
2181 if (!*argv)
2182 break;
2183 }
2184 }
2185 globfree(&globdata);
2186 }
2187 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002188}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002189/* Performs globbing on last list[],
2190 * saving each result as a new list[].
2191 */
2192static int o_glob(o_string *o, int n)
2193{
2194 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002195
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002196 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2197 if (!o->data)
2198 return o_save_ptr_helper(o, n);
2199 pattern = o->data + o_get_last_ptr(o, n);
2200 debug_printf_glob("glob pattern '%s'\n", pattern);
2201 if (!glob_needed(pattern)) {
2202 /* unbackslash last string in o in place, fix length */
2203 o->length = unbackslash(pattern) - o->data;
2204 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2205 return o_save_ptr_helper(o, n);
2206 }
2207
2208 copy = xstrdup(pattern);
2209 /* "forget" pattern in o */
2210 o->length = pattern - o->data;
2211 n = glob_brace(copy, o, n);
2212 free(copy);
2213 if (DEBUG_GLOB)
2214 debug_print_list("o_glob returning", o, n);
2215 return n;
2216}
2217
2218#else
2219
2220/* Helper */
2221static int glob_needed(const char *s)
2222{
2223 while (*s) {
2224 if (*s == '\\') {
2225 if (!s[1])
2226 return 0;
2227 s += 2;
2228 continue;
2229 }
2230 if (*s == '*' || *s == '[' || *s == '?')
2231 return 1;
2232 s++;
2233 }
2234 return 0;
2235}
2236/* Performs globbing on last list[],
2237 * saving each result as a new list[].
2238 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002239static int o_glob(o_string *o, int n)
2240{
2241 glob_t globdata;
2242 int gr;
2243 char *pattern;
2244
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002245 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002246 if (!o->data)
2247 return o_save_ptr_helper(o, n);
2248 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002249 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002250 if (!glob_needed(pattern)) {
2251 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002252 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002253 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002254 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002255 return o_save_ptr_helper(o, n);
2256 }
2257
2258 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002259 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2260 * If we glob "*.\*" and don't find anything, we need
2261 * to fall back to using literal "*.*", but GLOB_NOCHECK
2262 * will return "*.\*"!
2263 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002264 gr = glob(pattern, 0, NULL, &globdata);
2265 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002266 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002267 if (gr == GLOB_NOMATCH) {
2268 globfree(&globdata);
2269 goto literal;
2270 }
2271 if (gr == GLOB_NOSPACE)
2272 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002273 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2274 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002275 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002276 }
2277 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2278 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002279 /* "forget" pattern in o */
2280 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002281 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002282 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002283 n = o_save_ptr_helper(o, n);
2284 argv++;
2285 if (!*argv)
2286 break;
2287 }
2288 }
2289 globfree(&globdata);
2290 if (DEBUG_GLOB)
2291 debug_print_list("o_glob returning", o, n);
2292 return n;
2293}
2294
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002295#endif
2296
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002297/* If o->o_glob == 1, glob the string so far remembered.
2298 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002299static int o_save_ptr(o_string *o, int n)
2300{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002301 if (o->o_glob) { /* if globbing is requested */
2302 /* If o->has_empty_slot, list[n] was already globbed
2303 * (if it was requested back then when it was filled)
2304 * so don't do that again! */
2305 if (!o->has_empty_slot)
2306 return o_glob(o, n); /* o_save_ptr_helper is inside */
2307 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002308 return o_save_ptr_helper(o, n);
2309}
2310
2311/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002312static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002313{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002314 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002315 int string_start;
2316
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002317 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2318 if (DEBUG_EXPAND)
2319 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002320 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002321 list = (char**)o->data;
2322 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2323 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002324 while (n) {
2325 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002326 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002327 }
2328 return list;
2329}
2330
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002331
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002332/* Expansion can recurse */
2333#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002334static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002335#endif
2336static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002337#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002338#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002339 parse_stream_dquoted(dest, input, dquote_end)
2340#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002341static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002342 o_string *dest,
2343 struct in_str *input,
2344 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002345
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002346/* expand_strvec_to_strvec() takes a list of strings, expands
2347 * all variable references within and returns a pointer to
2348 * a list of expanded strings, possibly with larger number
2349 * of strings. (Think VAR="a b"; echo $VAR).
2350 * This new list is allocated as a single malloc block.
2351 * NULL-terminated list of char* pointers is at the beginning of it,
2352 * followed by strings themself.
2353 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002354
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002355/* Store given string, finalizing the word and starting new one whenever
2356 * we encounter IFS char(s). This is used for expanding variable values.
2357 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2358static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002359{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002360 while (1) {
2361 int word_len = strcspn(str, G.ifs);
2362 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002363 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002364 o_addQstr(output, str, word_len);
2365 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002366 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002367 str += word_len;
2368 }
2369 if (!*str) /* EOL - do not finalize word */
2370 break;
2371 o_addchr(output, '\0');
2372 debug_print_list("expand_on_ifs", output, n);
2373 n = o_save_ptr(output, n);
2374 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002375 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002376 debug_print_list("expand_on_ifs[1]", output, n);
2377 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002378}
2379
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002380/* Helper to expand $((...)) and heredoc body. These act as if
2381 * they are in double quotes, with the exception that they are not :).
2382 * Just the rules are similar: "expand only $var and `cmd`"
2383 *
2384 * Returns malloced string.
2385 * As an optimization, we return NULL if expansion is not needed.
2386 */
2387static char *expand_pseudo_dquoted(const char *str)
2388{
2389 char *exp_str;
2390 struct in_str input;
2391 o_string dest = NULL_O_STRING;
2392
2393 if (strchr(str, '$') == NULL
2394#if ENABLE_HUSH_TICK
2395 && strchr(str, '`') == NULL
2396#endif
2397 ) {
2398 return NULL;
2399 }
2400
2401 /* We need to expand. Example:
2402 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2403 */
2404 setup_string_in_str(&input, str);
2405 parse_stream_dquoted(NULL, &dest, &input, EOF);
2406 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2407 exp_str = expand_string_to_string(dest.data);
2408 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2409 o_free_unsafe(&dest);
2410 return exp_str;
2411}
2412
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002413#if ENABLE_SH_MATH_SUPPORT
2414static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2415{
2416 arith_eval_hooks_t hooks;
2417 arith_t res;
2418 char *exp_str;
2419
2420 hooks.lookupvar = get_local_var_value;
2421 hooks.setvar = set_local_var_from_halves;
2422 hooks.endofname = endofname;
2423 exp_str = expand_pseudo_dquoted(arg);
2424 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2425 free(exp_str);
2426 return res;
2427}
2428#endif
2429
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002430/* Expand all variable references in given string, adding words to list[]
2431 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2432 * to be filled). This routine is extremely tricky: has to deal with
2433 * variables/parameters with whitespace, $* and $@, and constructs like
2434 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02002435static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002436{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002437 /* or_mask is either 0 (normal case) or 0x80 -
2438 * expansion of right-hand side of assignment == 1-element expand.
2439 * It will also do no globbing, and thus we must not backslash-quote!
2440 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002441 char ored_ch;
2442 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002443
2444 ored_ch = 0;
2445
Denys Vlasenkof37eb392009-10-18 11:46:35 +02002446 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002447 debug_print_list("expand_vars_to_list", output, n);
2448 n = o_save_ptr(output, n);
2449 debug_print_list("expand_vars_to_list[0]", output, n);
2450
2451 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002452 char first_ch;
2453 int i;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002454 char *to_be_freed = NULL;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002455 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002456#if ENABLE_HUSH_TICK
2457 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002458#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002459#if ENABLE_SH_MATH_SUPPORT
2460 char arith_buf[sizeof(arith_t)*3 + 2];
2461#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002462 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002463 debug_print_list("expand_vars_to_list[1]", output, n);
2464 arg = ++p;
2465 p = strchr(p, SPECIAL_VAR_SYMBOL);
2466
2467 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2468 /* "$@" is special. Even if quoted, it can still
2469 * expand to nothing (not even an empty string) */
2470 if ((first_ch & 0x7f) != '@')
2471 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002472
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002473 switch (first_ch & 0x7f) {
2474 /* Highest bit in first_ch indicates that var is double-quoted */
2475 case '$': /* pid */
2476 val = utoa(G.root_pid);
2477 break;
2478 case '!': /* bg pid */
2479 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2480 break;
2481 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002482 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483 break;
2484 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002485 if (arg[1] != SPECIAL_VAR_SYMBOL)
2486 /* actually, it's a ${#var} */
2487 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002488 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2489 break;
2490 case '*':
2491 case '@':
2492 i = 1;
2493 if (!G.global_argv[i])
2494 break;
2495 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2496 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002497 smallint sv = output->o_escape;
2498 /* unquoted var's contents should be globbed, so don't escape */
2499 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002500 while (G.global_argv[i]) {
2501 n = expand_on_ifs(output, n, G.global_argv[i]);
2502 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2503 if (G.global_argv[i++][0] && G.global_argv[i]) {
2504 /* this argv[] is not empty and not last:
2505 * put terminating NUL, start new word */
2506 o_addchr(output, '\0');
2507 debug_print_list("expand_vars_to_list[2]", output, n);
2508 n = o_save_ptr(output, n);
2509 debug_print_list("expand_vars_to_list[3]", output, n);
2510 }
2511 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002512 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002513 } else
2514 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2515 * and in this case should treat it like '$*' - see 'else...' below */
2516 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2517 while (1) {
2518 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2519 if (++i >= G.global_argc)
2520 break;
2521 o_addchr(output, '\0');
2522 debug_print_list("expand_vars_to_list[4]", output, n);
2523 n = o_save_ptr(output, n);
2524 }
2525 } else { /* quoted $*: add as one word */
2526 while (1) {
2527 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2528 if (!G.global_argv[++i])
2529 break;
2530 if (G.ifs[0])
2531 o_addchr(output, G.ifs[0]);
2532 }
2533 }
2534 break;
2535 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2536 /* "Empty variable", used to make "" etc to not disappear */
2537 arg++;
2538 ored_ch = 0x80;
2539 break;
2540#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002541 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002542 *p = '\0';
2543 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002544 /* Can't just stuff it into output o_string,
2545 * expanded result may need to be globbed
2546 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002547 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko647553a2009-11-15 19:58:19 +01002548 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenkocddbb612010-05-20 14:27:09 +02002549 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002550 val = subst_result.data;
2551 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002552#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002553#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002554 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002555 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002556 int errcode;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002557
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002558 arg++; /* skip '+' */
2559 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002560 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002561 res = expand_and_evaluate_arith(arg, &errcode);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002562
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002563 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002564 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002565 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002566 case -3:
2567 msg = "exponent less than 0";
2568 break;
2569 case -2:
2570 msg = "divide by 0";
2571 break;
2572 case -5:
2573 msg = "expression recursion loop detected";
2574 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002575 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002576 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002577 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002578 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002579 sprintf(arith_buf, arith_t_fmt, res);
2580 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002581 break;
2582 }
2583#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002584 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002585 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002586 char *var = arg;
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002587 char exp_len; /* '#' if it's ${#var} */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002588 char exp_op;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002589 char exp_save = exp_save; /* for compiler */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002590 char *exp_saveptr = exp_saveptr; /* points to expansion operator */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002591 char *exp_word = exp_word; /* for compiler */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002592
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002593 *p = '\0';
2594 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002595
2596 /* prepare for expansions */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002597 exp_op = 0;
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002598 exp_len = var[0];
2599 if (exp_len == '#') {
Mike Frysinger6379bb42009-03-28 18:55:03 +00002600 /* handle length expansion ${#var} */
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002601 var++;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002602 } else {
2603 /* maybe handle parameter expansion */
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002604 exp_saveptr = var + strcspn(var, "%#:-=+?");
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002605 exp_op = exp_save = *exp_saveptr;
2606 if (exp_op) {
2607 exp_word = exp_saveptr + 1;
2608 if (exp_op == ':') {
2609 exp_op = *exp_word++;
2610 if (ENABLE_HUSH_BASH_COMPAT
2611 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2612 ) {
2613 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2614 exp_op = ':';
2615 exp_word--;
2616 }
2617 }
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002618 *exp_saveptr = '\0';
Mike Frysinger6379bb42009-03-28 18:55:03 +00002619 }
2620 }
2621
2622 /* lookup the variable in question */
2623 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002624 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002625 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002626 if (i < G.global_argc)
2627 val = G.global_argv[i];
2628 /* else val remains NULL: $N with too big N */
2629 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002630 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002631
2632 /* handle any expansions */
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002633 if (exp_len == '#') {
2634 debug_printf_expand("expand: length(%s)=", val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002635 val = utoa(val ? strlen(val) : 0);
2636 debug_printf_expand("%s\n", val);
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002637 } else if (exp_op) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002638 if (exp_op == '%' || exp_op == '#') {
Denys Vlasenko53b51332010-05-20 21:46:45 +02002639 /* Standard-mandated substring removal ops:
2640 * ${parameter%word} - remove smallest suffix pattern
2641 * ${parameter%%word} - remove largest suffix pattern
2642 * ${parameter#word} - remove smallest prefix pattern
2643 * ${parameter##word} - remove largest prefix pattern
2644 *
2645 * Word is expanded to produce a glob pattern.
2646 * Then var's value is matched to it and matching part removed.
2647 */
Mike Frysinger57e74672009-04-09 23:00:33 +00002648 if (val) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002649 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002650 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002651 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002652 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002653 exp_word++;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002654 val = to_be_freed = xstrdup(val);
Denys Vlasenko74369502010-05-21 19:52:01 +02002655 {
2656 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2657 if (exp_exp_word)
2658 exp_word = exp_exp_word;
2659 loc = scan(to_be_freed, exp_word, match_at_left);
2660 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2661 // exp_op, to_be_freed, exp_word, loc);
2662 free(exp_exp_word);
2663 }
2664 if (loc) { /* match was found */
2665 if (match_at_left) /* # or ## */
2666 val = loc;
2667 else /* % or %% */
2668 *loc = '\0';
2669 }
Mike Frysinger57e74672009-04-09 23:00:33 +00002670 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002671 } else if (exp_op == ':') {
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002672#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002673 /* It's ${var:N[:M]} bashism.
2674 * Note that in encoded form it has TWO parts:
2675 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002676 */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002677 arith_t beg, len;
2678 int errcode = 0;
2679
2680 beg = expand_and_evaluate_arith(exp_word, &errcode);
2681 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2682 *p++ = SPECIAL_VAR_SYMBOL;
2683 exp_word = p;
2684 p = strchr(p, SPECIAL_VAR_SYMBOL);
2685 *p = '\0';
2686 len = expand_and_evaluate_arith(exp_word, &errcode);
2687 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2688
2689 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2690 if (beg < 0) /* bash compat */
2691 beg = 0;
2692 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002693 if (len == 0 || !val || beg >= strlen(val))
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002694 val = "";
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002695 else {
2696 /* Paranoia. What if user entered 9999999999999
2697 * which fits in arith_t but not int? */
2698 if (len >= INT_MAX)
2699 len = INT_MAX;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002700 val = to_be_freed = xstrndup(val + beg, len);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002701 }
2702 debug_printf_varexp("val:'%s'\n", val);
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002703 } else
2704#endif
2705 {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002706 die_if_script("malformed ${%s:...}", var);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002707 val = "";
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002708 }
2709 } else { /* one of "-=+?" */
Denys Vlasenko53b51332010-05-20 21:46:45 +02002710 /* Standard-mandated substitution ops:
2711 * ${var?word} - indicate error if unset
2712 * If var is unset, word (or a message indicating it is unset
2713 * if word is null) is written to standard error
2714 * and the shell exits with a non-zero exit status.
2715 * Otherwise, the value of var is substituted.
2716 * ${var-word} - use default value
2717 * If var is unset, word is substituted.
2718 * ${var=word} - assign and use default value
2719 * If var is unset, word is assigned to var.
2720 * In all cases, final value of var is substituted.
2721 * ${var+word} - use alternative value
2722 * If var is unset, null is substituted.
2723 * Otherwise, word is substituted.
2724 *
2725 * Word is subjected to tilde expansion, parameter expansion,
2726 * command substitution, and arithmetic expansion.
2727 * If word is not needed, it is not expanded.
2728 *
2729 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2730 * but also treat null var as if it is unset.
2731 */
2732 int use_word = (!val || ((exp_save == ':') && !val[0]));
Mike Frysingera4f331d2009-04-07 06:03:22 +00002733 if (exp_op == '+')
Denys Vlasenko53b51332010-05-20 21:46:45 +02002734 use_word = !use_word;
Mike Frysingera4f331d2009-04-07 06:03:22 +00002735 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
Denys Vlasenko53b51332010-05-20 21:46:45 +02002736 (exp_save == ':') ? "true" : "false", use_word);
2737 if (use_word) {
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002738 to_be_freed = expand_pseudo_dquoted(exp_word);
2739 if (to_be_freed)
2740 exp_word = to_be_freed;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002741 if (exp_op == '?') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002742 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002743 die_if_script("%s: %s",
2744 var,
2745 exp_word[0] ? exp_word : "parameter null or not set"
2746 );
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002747//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002748 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002749 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002750 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002751
Mike Frysingera4f331d2009-04-07 06:03:22 +00002752 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002753 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002754 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002755 /* mimic bash message */
2756 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002757 val = NULL;
2758 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002759 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002760 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002761 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002762 }
2763 }
2764 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002765
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002766 *exp_saveptr = exp_save;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002767 } /* if (exp_op) */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002768
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002769 arg[0] = first_ch;
2770#if ENABLE_HUSH_TICK
2771 store_val:
2772#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002773 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002774 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002775 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002776 /* unquoted var's contents should be globbed, so don't escape */
2777 smallint sv = output->o_escape;
2778 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002779 n = expand_on_ifs(output, n, val);
2780 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002781 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002782 }
2783 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002784 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002785 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002786 } /* default: */
2787 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002788
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789 if (val) {
2790 o_addQstr(output, val, strlen(val));
2791 }
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002792 free(to_be_freed);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002793 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002794 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002795 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002796
2797#if ENABLE_HUSH_TICK
2798 o_free(&subst_result);
2799#endif
2800 arg = ++p;
2801 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2802
2803 if (arg[0]) {
2804 debug_print_list("expand_vars_to_list[a]", output, n);
2805 /* this part is literal, and it was already pre-quoted
2806 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002807 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002808 debug_print_list("expand_vars_to_list[b]", output, n);
2809 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2810 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2811 ) {
2812 n--;
2813 /* allow to reuse list[n] later without re-growth */
2814 output->has_empty_slot = 1;
2815 } else {
2816 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002817 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002818 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002819}
2820
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002821static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002822{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002823 int n;
2824 char **list;
2825 char **v;
2826 o_string output = NULL_O_STRING;
2827
2828 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002829 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002830 /* (unquoted $var will temporarily switch it off) */
2831 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002832 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002833
2834 n = 0;
2835 v = argv;
2836 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002837 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002838 v++;
2839 }
2840 debug_print_list("expand_variables", &output, n);
2841
2842 /* output.data (malloced in one block) gets returned in "list" */
2843 list = o_finalize_list(&output, n);
2844 debug_print_strings("expand_variables[1]", list);
2845 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002846}
2847
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002848static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002849{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002850 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002851}
2852
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002853#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002854static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2855{
2856 return expand_variables(argv, 0x80);
2857}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002858#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002859
2860#ifdef CMD_SINGLEWORD_NOGLOB_COND
2861static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2862{
2863 int n;
2864 char **list;
2865 char **v;
2866 o_string output = NULL_O_STRING;
2867
2868 n = 0;
2869 v = argv;
2870 while (*v) {
2871 int is_var = is_well_formed_var_name(*v, '=');
2872 /* is_var * 0x80: singleword expansion for vars */
2873 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2874
2875 /* Subtle! expand_vars_to_list did not glob last word yet.
2876 * It does this only when fed with further data.
2877 * Therefore we set globbing flags AFTER it, not before:
2878 */
2879
2880 /* if it is not recognizably abc=...; then: */
2881 output.o_escape = !is_var; /* protect against globbing for "$var" */
2882 /* (unquoted $var will temporarily switch it off) */
2883 output.o_glob = !is_var; /* and indeed do globbing */
2884 v++;
2885 }
2886 debug_print_list("expand_cond", &output, n);
2887
2888 /* output.data (malloced in one block) gets returned in "list" */
2889 list = o_finalize_list(&output, n);
2890 debug_print_strings("expand_cond[1]", list);
2891 return list;
2892}
2893#endif
2894
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002895/* Used for expansion of right hand of assignments */
2896/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2897 * "v=/bin/c*" */
2898static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002899{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002900 char *argv[2], **list;
2901
2902 argv[0] = (char*)str;
2903 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002904 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002905 if (HUSH_DEBUG)
2906 if (!list[0] || list[1])
2907 bb_error_msg_and_die("BUG in varexp2");
2908 /* actually, just move string 2*sizeof(char*) bytes back */
2909 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002910 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002911 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2912 return (char*)list;
2913}
2914
2915/* Used for "eval" builtin */
2916static char* expand_strvec_to_string(char **argv)
2917{
2918 char **list;
2919
2920 list = expand_variables(argv, 0x80);
2921 /* Convert all NULs to spaces */
2922 if (list[0]) {
2923 int n = 1;
2924 while (list[n]) {
2925 if (HUSH_DEBUG)
2926 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2927 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002928 /* bash uses ' ' regardless of $IFS contents */
2929 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002930 n++;
2931 }
2932 }
2933 overlapping_strcpy((char*)list, list[0]);
2934 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2935 return (char*)list;
2936}
2937
2938static char **expand_assignments(char **argv, int count)
2939{
2940 int i;
2941 char **p = NULL;
2942 /* Expand assignments into one string each */
2943 for (i = 0; i < count; i++) {
2944 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2945 }
2946 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002947}
2948
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002949
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002950#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002951/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002952void re_execute_shell(char ***to_free, const char *s,
2953 char *g_argv0, char **g_argv,
2954 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002955
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002956static void reset_traps_to_defaults(void)
2957{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002958 /* This function is always called in a child shell
2959 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002960 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002961 unsigned sig;
2962 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002963
Denys Vlasenko67f71862009-09-25 14:21:06 +02002964 /* Child shells are not interactive.
2965 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2966 * Testcase: (while :; do :; done) + ^Z should background.
2967 * Same goes for SIGTERM, SIGHUP, SIGINT.
2968 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002969 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02002970 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002971
Denys Vlasenko67f71862009-09-25 14:21:06 +02002972 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2973 * Stupid. It can be done with *single* &= op, but we can't use
2974 * the fact that G.blocked_set is implemented as a bitmask
2975 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002976 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2977 sig = 1;
2978 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002979 if (mask & 1) {
2980 /* Careful. Only if no trap or trap is not "" */
2981 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2982 sigdelset(&G.blocked_set, sig);
2983 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002984 mask >>= 1;
2985 if (!mask)
2986 break;
2987 sig++;
2988 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02002989 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002990 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002991
2992 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002993 mask = G.non_DFL_mask;
2994 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002995 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002996 continue;
2997 free(G.traps[sig]);
2998 G.traps[sig] = NULL;
2999 /* There is no signal for 0 (EXIT) */
3000 if (sig == 0)
3001 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003002 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003003 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02003004 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003005 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003006 continue;
3007 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003008 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003009 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003010}
3011
3012#else /* !BB_MMU */
3013
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003014static void re_execute_shell(char ***to_free, const char *s,
3015 char *g_argv0, char **g_argv,
3016 char **builtin_argv) NORETURN;
3017static void re_execute_shell(char ***to_free, const char *s,
3018 char *g_argv0, char **g_argv,
3019 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003020{
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003021#define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
3022 /* delims + 2 * (number of bytes in printed hex numbers) */
3023 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003024 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003025 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003026# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003027 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003028# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003029 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003030 unsigned cnt;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003031 unsigned long long empty_trap_mask;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003032
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003033 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003034 argv = heredoc_argv;
3035 argv[0] = (char *) G.argv0_for_re_execing;
3036 argv[1] = (char *) "-<";
3037 argv[2] = (char *) s;
3038 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00003039 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003040 goto do_exec;
3041 }
3042
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003043 cnt = 0;
3044 pp = builtin_argv;
3045 if (pp) while (*pp++)
3046 cnt++;
3047
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003048 empty_trap_mask = 0;
3049 if (G.traps) {
3050 int sig;
3051 for (sig = 1; sig < NSIG; sig++) {
3052 if (G.traps[sig] && !G.traps[sig][0])
3053 empty_trap_mask |= 1LL << sig;
3054 }
3055 }
3056
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003057 sprintf(param_buf, NOMMU_HACK_FMT
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003058 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02003059 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003060 , (unsigned) G.last_bg_pid
3061 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003062 , cnt
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003063 , empty_trap_mask
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003064 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003065 );
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003066#undef NOMMU_HACK_FMT
3067 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003068 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003069 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003070 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003071 for (cur = G.top_var; cur; cur = cur->next) {
3072 if (!cur->flg_export || cur->flg_read_only)
3073 cnt += 2;
3074 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003075# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003076 for (funcp = G.top_func; funcp; funcp = funcp->next)
3077 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003078# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003079 pp = g_argv;
3080 while (*pp++)
3081 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003082 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003083 *pp++ = (char *) G.argv0_for_re_execing;
3084 *pp++ = param_buf;
3085 for (cur = G.top_var; cur; cur = cur->next) {
3086 if (cur->varstr == hush_version_str)
3087 continue;
3088 if (cur->flg_read_only) {
3089 *pp++ = (char *) "-R";
3090 *pp++ = cur->varstr;
3091 } else if (!cur->flg_export) {
3092 *pp++ = (char *) "-V";
3093 *pp++ = cur->varstr;
3094 }
3095 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003096# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003097 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3098 *pp++ = (char *) "-F";
3099 *pp++ = funcp->name;
3100 *pp++ = funcp->body_as_string;
3101 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003102# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003103 /* We can pass activated traps here. Say, -Tnn:trap_string
3104 *
3105 * However, POSIX says that subshells reset signals with traps
3106 * to SIG_DFL.
3107 * I tested bash-3.2 and it not only does that with true subshells
3108 * of the form ( list ), but with any forked children shells.
3109 * I set trap "echo W" WINCH; and then tried:
3110 *
3111 * { echo 1; sleep 20; echo 2; } &
3112 * while true; do echo 1; sleep 20; echo 2; break; done &
3113 * true | { echo 1; sleep 20; echo 2; } | cat
3114 *
3115 * In all these cases sending SIGWINCH to the child shell
3116 * did not run the trap. If I add trap "echo V" WINCH;
3117 * _inside_ group (just before echo 1), it works.
3118 *
3119 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003120 * Even if we would use signal handlers instead of signal masking
3121 * in order to implement trap handling,
3122 * exec syscall below resets signals to SIG_DFL for us.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003123 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003124 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003125 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003126 if (builtin_argv) {
3127 while (*++builtin_argv)
3128 *pp++ = *builtin_argv;
3129 *pp++ = (char *) "";
3130 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003131 *pp++ = g_argv0;
3132 while (*g_argv)
3133 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003134 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003135 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003136
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003137 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003138 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3139 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003140 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003141 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003142 if (argv[0][0] == '/')
3143 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003144 xfunc_error_retval = 127;
3145 bb_error_msg_and_die("can't re-execute the shell");
3146}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003147#endif /* !BB_MMU */
3148
3149
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003150static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003151{
3152 struct fd_pair pair;
3153 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003154 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003155 /* the _body_ of heredoc (misleading field name) */
3156 const char *heredoc = redir->rd_filename;
3157 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003158#if !BB_MMU
3159 char **to_free;
3160#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003161
3162 expanded = NULL;
3163 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3164 expanded = expand_pseudo_dquoted(heredoc);
3165 if (expanded)
3166 heredoc = expanded;
3167 }
3168 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003169
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003170 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003171 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003172 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003173
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003174 /* Try writing without forking. Newer kernels have
3175 * dynamically growing pipes. Must use non-blocking write! */
3176 ndelay_on(pair.wr);
3177 while (1) {
3178 written = write(pair.wr, heredoc, len);
3179 if (written <= 0)
3180 break;
3181 len -= written;
3182 if (len == 0) {
3183 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00003184 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003185 return;
3186 }
3187 heredoc += written;
3188 }
3189 ndelay_off(pair.wr);
3190
3191 /* Okay, pipe buffer was not big enough */
3192 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003193 * for the unsuspecting parent process. Child creates a grandchild
3194 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003195 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003196#if !BB_MMU
3197 to_free = NULL;
3198#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003199 pid = vfork();
3200 if (pid < 0)
3201 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003202 if (pid == 0) {
3203 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003204 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003205 pid = BB_MMU ? fork() : vfork();
3206 if (pid < 0)
3207 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3208 if (pid != 0)
3209 _exit(0);
3210 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003211 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003212#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003213 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003214 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003215#else
3216 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003217 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003218 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003219#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003220 }
3221 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003222#if ENABLE_HUSH_FAST
3223 G.count_SIGCHLD++;
3224//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3225#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003226 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003227#if !BB_MMU
3228 free(to_free);
3229#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003230 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003231 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003232 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003233}
3234
Eric Andersen25f27032001-04-26 23:22:31 +00003235/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3236 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003237static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003238{
3239 int openfd, mode;
3240 struct redir_struct *redir;
3241
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003242 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003243 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003244 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003245 if (squirrel && redir->rd_fd < 3
3246 && squirrel[redir->rd_fd] < 0
3247 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003248 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003249 }
3250 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3251 * of the heredoc */
3252 debug_printf_parse("set heredoc '%s'\n",
3253 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003254 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003255 continue;
3256 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003257
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003258 if (redir->rd_dup == REDIRFD_TO_FILE) {
3259 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003260 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003261 if (redir->rd_filename == NULL) {
3262 /* Something went wrong in the parse.
3263 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003264 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003265 continue;
3266 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003267 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003268 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003269 openfd = open_or_warn(p, mode);
3270 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003271 if (openfd < 0) {
3272 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003273 * bash and ash both lose it as well (though zsh doesn't!) */
3274//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003275 return 1;
3276 }
3277 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003278 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003279 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003280 }
3281
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003282 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003283 if (squirrel && redir->rd_fd < 3
3284 && squirrel[redir->rd_fd] < 0
3285 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003286 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003287 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003288 if (openfd == REDIRFD_CLOSE) {
3289 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003290 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003291 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003292 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003293 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003294 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003295 }
Eric Andersen25f27032001-04-26 23:22:31 +00003296 }
3297 }
3298 return 0;
3299}
3300
3301static void restore_redirects(int squirrel[])
3302{
3303 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003304 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003305 fd = squirrel[i];
3306 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003307 /* We simply die on error */
3308 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003309 }
3310 }
3311}
3312
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003313
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003314static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003315
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003316/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003317static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003318{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003319 char **p;
3320 struct command *command;
3321 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003322 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003323
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003324 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003325 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003326 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003327 for (i = 0; i < pi->num_cmds; i++) {
3328 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003329 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003330 if (command->argv) {
3331 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003332 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003333 }
3334 free_strings(command->argv);
3335 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003336 }
3337 /* not "else if": on syntax error, we may have both! */
3338 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003339 debug_printf_clean(" begin group (cmd_type:%d)\n",
3340 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003341 free_pipe_list(command->group);
3342 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003343 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003344 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003345 /* else is crucial here.
3346 * If group != NULL, child_func is meaningless */
3347#if ENABLE_HUSH_FUNCTIONS
3348 else if (command->child_func) {
3349 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3350 command->child_func->parent_cmd = NULL;
3351 }
3352#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003353#if !BB_MMU
3354 free(command->group_as_string);
3355 command->group_as_string = NULL;
3356#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003357 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003358 debug_printf_clean(" redirect %d%s",
3359 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003360 /* guard against the case >$FOO, where foo is unset or blank */
3361 if (r->rd_filename) {
3362 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3363 free(r->rd_filename);
3364 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003365 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003366 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003367 rnext = r->next;
3368 free(r);
3369 }
3370 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003371 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003372 free(pi->cmds); /* children are an array, they get freed all at once */
3373 pi->cmds = NULL;
3374#if ENABLE_HUSH_JOB
3375 free(pi->cmdtext);
3376 pi->cmdtext = NULL;
3377#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003378}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003379
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003380static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003381{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003382 struct pipe *pi, *next;
3383
3384 for (pi = head; pi; pi = next) {
3385#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003386 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003387#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003388 free_pipe(pi);
3389 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003390 next = pi->next;
3391 /*pi->next = NULL;*/
3392 free(pi);
3393 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003394}
3395
3396
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003397static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003398#if BB_MMU
3399#define parse_stream(pstring, input, end_trigger) \
3400 parse_stream(input, end_trigger)
3401#endif
3402static struct pipe *parse_stream(char **pstring,
3403 struct in_str *input,
3404 int end_trigger);
3405static void parse_and_run_string(const char *s);
3406
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003407
Mike Frysinger93cadc22009-05-27 17:06:25 -04003408static char *find_in_path(const char *arg)
3409{
3410 char *ret = NULL;
3411 const char *PATH = get_local_var_value("PATH");
3412
3413 if (!PATH)
3414 return NULL;
3415
3416 while (1) {
3417 const char *end = strchrnul(PATH, ':');
3418 int sz = end - PATH; /* must be int! */
3419
3420 free(ret);
3421 if (sz != 0) {
3422 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3423 } else {
3424 /* We have xxx::yyyy in $PATH,
3425 * it means "use current dir" */
3426 ret = xstrdup(arg);
3427 }
3428 if (access(ret, F_OK) == 0)
3429 break;
3430
3431 if (*end == '\0') {
3432 free(ret);
3433 return NULL;
3434 }
3435 PATH = end + 1;
3436 }
3437
3438 return ret;
3439}
3440
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003441static const struct built_in_command* find_builtin_helper(const char *name,
3442 const struct built_in_command *x,
3443 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003444{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003445 while (x != end) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01003446 if (strcmp(name, x->b_cmd) != 0) {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003447 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003448 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003449 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003450 debug_printf_exec("found builtin '%s'\n", name);
3451 return x;
3452 }
3453 return NULL;
3454}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003455static const struct built_in_command* find_builtin1(const char *name)
3456{
3457 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3458}
3459static const struct built_in_command* find_builtin(const char *name)
3460{
3461 const struct built_in_command *x = find_builtin1(name);
3462 if (x)
3463 return x;
3464 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3465}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003466
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003467#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003468static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003469{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003470 struct function **funcpp = &G.top_func;
3471 while (*funcpp) {
3472 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003473 break;
3474 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003475 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003476 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003477 return funcpp;
3478}
3479
3480static const struct function *find_function(const char *name)
3481{
3482 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003483 if (funcp)
3484 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003485 return funcp;
3486}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003487
Denis Vlasenkobc569742009-04-12 20:35:19 +00003488/* Note: takes ownership on name ptr */
3489static struct function *new_function(char *name)
3490{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003491 struct function **funcpp = find_function_slot(name);
3492 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003493
Denys Vlasenko873273d2009-09-12 14:47:41 +02003494 if (funcp != NULL) {
3495 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003496 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3497 if (!cmd) {
3498 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3499 free(funcp->name);
3500 /* Note: if !funcp->body, do not free body_as_string!
3501 * This is a special case of "-F name body" function:
3502 * body_as_string was not malloced! */
3503 if (funcp->body) {
3504 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003505# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003506 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003507# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003508 }
3509 } else {
3510 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3511 cmd->argv[0] = funcp->name;
3512 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003513# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003514 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003515# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003516 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003517 } else {
3518 debug_printf_exec("remembering new function '%s'\n", name);
3519 funcp = *funcpp = xzalloc(sizeof(*funcp));
3520 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003521 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003522
Denis Vlasenkobc569742009-04-12 20:35:19 +00003523 funcp->name = name;
3524 return funcp;
3525}
3526
Denis Vlasenko40e84372009-04-18 11:23:38 +00003527static void unset_func(const char *name)
3528{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003529 struct function **funcpp = find_function_slot(name);
3530 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003531
Denys Vlasenko873273d2009-09-12 14:47:41 +02003532 if (funcp != NULL) {
3533 debug_printf_exec("freeing function '%s'\n", funcp->name);
3534 *funcpp = funcp->next;
3535 /* funcp is unlinked now, deleting it.
3536 * Note: if !funcp->body, the function was created by
3537 * "-F name body", do not free ->body_as_string
3538 * and ->name as they were not malloced. */
3539 if (funcp->body) {
3540 free_pipe_list(funcp->body);
3541 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003542# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003543 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003544# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003545 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003546 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003547 }
3548}
3549
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003550# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003551#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003552 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003553# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003554static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003555 const struct function *funcp,
3556 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003557static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003558 const struct function *funcp,
3559 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003560{
3561# if BB_MMU
3562 int n = 1;
3563
3564 argv[0] = G.global_argv[0];
3565 G.global_argv = argv;
3566 while (*++argv)
3567 n++;
3568 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003569 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003570 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003571 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003572 _exit(n);
3573# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003574 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003575 funcp->body_as_string,
3576 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003577 argv + 1,
3578 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003579# endif
3580}
3581
3582static int run_function(const struct function *funcp, char **argv)
3583{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003584 int rc;
3585 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003586 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003587
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003588 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003589
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003590 /* "we are in function, ok to use return" */
3591 sv_flg = G.flag_return_in_progress;
3592 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003593# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003594 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003595# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003596
Denis Vlasenkobc569742009-04-12 20:35:19 +00003597 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003598# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003599 if (!funcp->body) {
3600 /* Function defined by -F */
3601 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003602 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003603 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003604# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003605 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003606 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003607 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003608
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003609# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003610 {
3611 struct variable *var;
3612 struct variable **var_pp;
3613
3614 var_pp = &G.top_var;
3615 while ((var = *var_pp) != NULL) {
3616 if (var->func_nest_level < G.func_nest_level) {
3617 var_pp = &var->next;
3618 continue;
3619 }
3620 /* Unexport */
3621 if (var->flg_export)
3622 bb_unsetenv(var->varstr);
3623 /* Remove from global list */
3624 *var_pp = var->next;
3625 /* Free */
3626 if (!var->max_len)
3627 free(var->varstr);
3628 free(var);
3629 }
3630 G.func_nest_level--;
3631 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003632# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003633 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003634
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003635 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003636
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003637 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003638}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003639#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003640
3641
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003642#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003643#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003644 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003645#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003646#define exec_builtin(to_free, x, argv) \
3647 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003648#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003649static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003650 const struct built_in_command *x,
3651 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003652static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003653 const struct built_in_command *x,
3654 char **argv)
3655{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003656#if BB_MMU
Denys Vlasenko17323a62010-01-28 01:57:05 +01003657 int rcode = x->b_function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003658 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003659 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003660#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003661 /* On NOMMU, we must never block!
3662 * Example: { sleep 99 | read line; } & echo Ok
3663 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003664 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003665 argv[0],
3666 G.global_argv[0],
3667 G.global_argv + 1,
3668 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003669#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003670}
3671
3672
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003673static void execvp_or_die(char **argv) NORETURN;
3674static void execvp_or_die(char **argv)
3675{
3676 debug_printf_exec("execing '%s'\n", argv[0]);
3677 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3678 execvp(argv[0], argv);
3679 bb_perror_msg("can't execute '%s'", argv[0]);
3680 _exit(127); /* bash compat */
3681}
3682
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003683#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003684#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3685 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3686#define pseudo_exec(nommu_save, command, argv_expanded) \
3687 pseudo_exec(command, argv_expanded)
3688#endif
3689
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003690/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003691 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003692 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003693 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003694 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003695static void pseudo_exec_argv(nommu_save_t *nommu_save,
3696 char **argv, int assignment_cnt,
3697 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003698static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003699 char **argv, int assignment_cnt,
3700 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003701{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003702 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003703
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003704 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003705 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003706 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003707
Denis Vlasenko9504e442008-10-29 01:19:15 +00003708 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003709#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003710 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003711 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003712 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003713 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003714#else
3715 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003716 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003717#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003718 if (argv_expanded) {
3719 argv = argv_expanded;
3720 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003721 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003722#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003723 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003724#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003725 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003726
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003727#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3728 if (strchr(argv[0], '/') != NULL)
3729 goto skip;
3730#endif
3731
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003732 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003733 * Depending on context, this might be redundant. But it's
3734 * easier to waste a few CPU cycles than it is to figure out
3735 * if this is one of those cases.
3736 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003737 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003738 /* On NOMMU, it is more expensive to re-execute shell
3739 * just in order to run echo or test builtin.
3740 * It's better to skip it here and run corresponding
3741 * non-builtin later. */
3742 const struct built_in_command *x;
3743 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003744 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003745 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003746 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003747 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003748#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003749 /* Check if the command matches any functions */
3750 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003751 const struct function *funcp = find_function(argv[0]);
3752 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003753 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003754 }
3755 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003756#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003757
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003758#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003759 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003760 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003761 int a = find_applet_by_name(argv[0]);
3762 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003763# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003764 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003765 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003766 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003767 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003768# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003769 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003770 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003771 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3772 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003773 /* If they called chroot or otherwise made the binary no longer
3774 * executable, fall through */
3775 }
3776 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003777#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003778
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003779#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003780 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003781#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003782 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003783}
3784
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003785/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003786 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003787static void pseudo_exec(nommu_save_t *nommu_save,
3788 struct command *command,
3789 char **argv_expanded) NORETURN;
3790static void pseudo_exec(nommu_save_t *nommu_save,
3791 struct command *command,
3792 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003793{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003794 if (command->argv) {
3795 pseudo_exec_argv(nommu_save, command->argv,
3796 command->assignment_cnt, argv_expanded);
3797 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003798
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003799 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003800 /* Cases when we are here:
3801 * ( list )
3802 * { list } &
3803 * ... | ( list ) | ...
3804 * ... | { list } | ...
3805 */
3806#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003807 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003808 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003809 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003810 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003811 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003812 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003813 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003814#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003815 re_execute_shell(&nommu_save->argv_from_re_execing,
3816 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003817 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003818 G.global_argv + 1,
3819 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003820#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003821 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003822
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003823 /* Case when we are here: ... | >file */
3824 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003825 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003826}
3827
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003828#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003829static const char *get_cmdtext(struct pipe *pi)
3830{
3831 char **argv;
3832 char *p;
3833 int len;
3834
3835 /* This is subtle. ->cmdtext is created only on first backgrounding.
3836 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003837 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003838 if (pi->cmdtext)
3839 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003840 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003841 if (!argv || !argv[0]) {
3842 pi->cmdtext = xzalloc(1);
3843 return pi->cmdtext;
3844 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003845
3846 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003847 do {
3848 len += strlen(*argv) + 1;
3849 } while (*++argv);
3850 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003851 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003852 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003853 do {
3854 len = strlen(*argv);
3855 memcpy(p, *argv, len);
3856 p += len;
3857 *p++ = ' ';
3858 } while (*++argv);
3859 p[-1] = '\0';
3860 return pi->cmdtext;
3861}
3862
Eric Andersenbafd94f2001-05-02 16:11:59 +00003863static void insert_bg_job(struct pipe *pi)
3864{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003865 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003866 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003867
3868 /* Linear search for the ID of the job to use */
3869 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003870 for (job = G.job_list; job; job = job->next)
3871 if (job->jobid >= pi->jobid)
3872 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003873
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003874 /* Add job to the list of running jobs */
3875 jobp = &G.job_list;
3876 while ((job = *jobp) != NULL)
3877 jobp = &job->next;
3878 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003879
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003880 *job = *pi; /* physical copy */
3881 job->next = NULL;
3882 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3883 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003884 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003885 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003886 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003887 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003888 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003889
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003890 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003891 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3892 /* Last command's pid goes to $! */
3893 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3894 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003895}
3896
Eric Andersenbafd94f2001-05-02 16:11:59 +00003897static void remove_bg_job(struct pipe *pi)
3898{
3899 struct pipe *prev_pipe;
3900
Denis Vlasenko87a86552008-07-29 19:43:10 +00003901 if (pi == G.job_list) {
3902 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003903 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003904 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003905 while (prev_pipe->next != pi)
3906 prev_pipe = prev_pipe->next;
3907 prev_pipe->next = pi->next;
3908 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003909 if (G.job_list)
3910 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003911 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003912 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003913}
Eric Andersen028b65b2001-06-28 01:10:11 +00003914
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003915/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003916static void delete_finished_bg_job(struct pipe *pi)
3917{
3918 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003919 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003920 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003921 free(pi);
3922}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003923#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003924
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003925/* Check to see if any processes have exited -- if they
3926 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003927static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003928{
Eric Andersenc798b072001-06-22 06:23:03 +00003929 int attributes;
3930 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003931#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003932 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003933#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003934 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003935 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003936
Denis Vlasenkod5762932009-03-31 11:22:57 +00003937 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3938
Eric Andersenc798b072001-06-22 06:23:03 +00003939 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003940 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003941 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003942
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003943 errno = 0;
3944#if ENABLE_HUSH_FAST
3945 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3946//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3947//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003948 /* There was neither fork nor SIGCHLD since last waitpid */
3949 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003950 if (!G.we_have_children) {
3951 errno = ECHILD;
3952 return -1;
3953 }
3954 if (fg_pipe == NULL) { /* is WNOHANG set? */
3955 /* We have children, but they did not exit
3956 * or stop yet (we saw no SIGCHLD) */
3957 return 0;
3958 }
3959 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3960 }
3961#endif
3962
Denis Vlasenko1359da62007-04-21 23:27:30 +00003963/* Do we do this right?
3964 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003965 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003966 * [3]+ Stopped sleep 20 | false
3967 * bash-3.00# echo $?
3968 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003969 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003970 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003971 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003972 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003973 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003974 int dead;
3975
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003976#if ENABLE_HUSH_FAST
3977 i = G.count_SIGCHLD;
3978#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003979 childpid = waitpid(-1, &status, attributes);
3980 if (childpid <= 0) {
3981 if (childpid && errno != ECHILD)
3982 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003983#if ENABLE_HUSH_FAST
3984 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003985 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003986 G.handled_SIGCHLD = i;
3987//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3988 }
3989#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003990 break;
3991 }
3992 dead = WIFEXITED(status) || WIFSIGNALED(status);
3993
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003994#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003995 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003996 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003997 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3998 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003999 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004000 childpid, WTERMSIG(status), WEXITSTATUS(status));
4001 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004002 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004003 childpid, WEXITSTATUS(status));
4004#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004005 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00004006 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004007 for (i = 0; i < fg_pipe->num_cmds; i++) {
4008 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4009 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004010 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004011 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004012 fg_pipe->cmds[i].pid = 0;
4013 fg_pipe->alive_cmds--;
4014 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004015 /* last process gives overall exitstatus */
4016 rcode = WEXITSTATUS(status);
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004017 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00004018 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004019 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00004020 */
4021 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00004022 int sig = WTERMSIG(status);
4023 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004024 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4025 * Maybe we need to use sig | 128? */
4026 rcode = sig + 128;
Denis Vlasenko40e84372009-04-18 11:23:38 +00004027 }
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004028 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00004029 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004030 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004031 fg_pipe->cmds[i].is_stopped = 1;
4032 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00004033 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004034 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4035 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4036 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004037 /* All processes in fg pipe have exited or stopped */
4038/* Note: *non-interactive* bash does not continue if all processes in fg pipe
4039 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4040 * and "killall -STOP cat" */
4041 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004042#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004043 if (fg_pipe->alive_cmds)
4044 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004045#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004046 return rcode;
4047 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02004048 if (!fg_pipe->alive_cmds)
4049 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004050 }
4051 /* There are still running processes in the fg pipe */
4052 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00004053 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004054 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00004055 }
4056
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004057#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004058 /* We asked to wait for bg or orphaned children */
4059 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004060 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004061 for (i = 0; i < pi->num_cmds; i++) {
4062 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004063 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00004064 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00004065 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004066 /* Happens when shell is used as init process (init=/bin/sh) */
4067 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004068 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00004069
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004070 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00004071 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00004072 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004073 pi->cmds[i].pid = 0;
4074 pi->alive_cmds--;
4075 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004076 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00004077 printf(JOB_STATUS_FORMAT, pi->jobid,
4078 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004079 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004080 }
4081 } else {
4082 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004083 pi->cmds[i].is_stopped = 1;
4084 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004085 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004086#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004087 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004088
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004089 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00004090}
4091
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004092#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00004093static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4094{
4095 pid_t p;
4096 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04004097 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004098 /* Job finished, move the shell to the foreground */
4099 p = getpgrp(); /* our process group id */
4100 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4101 tcsetpgrp(G_interactive_fd, p);
4102 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00004103 return rcode;
4104}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004105#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00004106
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004107/* Start all the jobs, but don't wait for anything to finish.
4108 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00004109 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00004110 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00004111 * to finish to determine the exit status of the pipe. If the pipe
4112 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00004113 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00004114 * return value.
4115 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00004116 * Returns -1 only if started some children. IOW: we have to
4117 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00004118 *
4119 * The only case when we do not need to [v]fork is when the pipe
4120 * is single, non-backgrounded, non-subshell command. Examples:
4121 * cmd ; ... { list } ; ...
4122 * cmd && ... { list } && ...
4123 * cmd || ... { list } || ...
4124 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4125 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004126 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00004127 *
4128 * Cases when we must fork:
4129 * non-single: cmd | cmd
4130 * backgrounded: cmd & { list } &
4131 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00004132 */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02004133static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004134{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004135 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004136 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004137 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004138 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004139 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004140 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004141 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004142 /* it is not always needed, but we aim to smaller code */
4143 int squirrel[] = { -1, -1, -1 };
4144 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004145
Denis Vlasenko552433b2009-04-04 19:29:21 +00004146 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004147 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004148
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004149 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004150 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004151 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004152 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004153
Denis Vlasenko552433b2009-04-04 19:29:21 +00004154 if (pi->num_cmds != 1
4155 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004156 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00004157 ) {
4158 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004159 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004160
Denis Vlasenko552433b2009-04-04 19:29:21 +00004161 pi->alive_cmds = 1;
4162
4163 debug_printf_exec(": group:%p argv:'%s'\n",
4164 command->group, command->argv ? command->argv[0] : "NONE");
4165
4166 if (command->group) {
4167#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004168 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004169 /* "executing" func () { list } */
4170 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004171
Denis Vlasenkobc569742009-04-12 20:35:19 +00004172 funcp = new_function(command->argv[0]);
4173 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004174 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004175# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004176 funcp->body_as_string = command->group_as_string;
4177 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004178# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004179 command->group = NULL;
4180 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00004181 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4182 funcp->parent_cmd = command;
4183 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004184
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004185 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4186 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00004187 return EXIT_SUCCESS;
4188 }
4189#endif
4190 /* { list } */
4191 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004192 rcode = 1; /* exitcode if redir failed */
4193 if (setup_redirects(command, squirrel) == 0) {
4194 debug_printf_exec(": run_list\n");
4195 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004196 }
Eric Andersen04407e52001-06-07 16:42:05 +00004197 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004198 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004199 debug_leave();
4200 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004201 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004202 }
4203
Denis Vlasenko552433b2009-04-04 19:29:21 +00004204 argv = command->argv ? command->argv : (char **) &null_ptr;
4205 {
4206 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004207#if ENABLE_HUSH_FUNCTIONS
4208 const struct function *funcp;
4209#else
4210 enum { funcp = 0 };
4211#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004212 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004213 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004214
Denis Vlasenko552433b2009-04-04 19:29:21 +00004215 if (argv[command->assignment_cnt] == NULL) {
4216 /* Assignments, but no command */
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004217 /* Ensure redirects take effect (that is, create files).
4218 * Try "a=t >file": */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004219 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004220 restore_redirects(squirrel);
4221 /* Set shell variables */
4222 while (*argv) {
4223 p = expand_string_to_string(*argv);
4224 debug_printf_exec("set shell var:'%s'->'%s'\n",
4225 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004226 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004227 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004228 }
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004229 /* Redirect error sets $? to 1. Othervise,
4230 * if evaluating assignment value set $?, retain it.
4231 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4232 if (rcode == 0)
4233 rcode = G.last_exitcode;
Denis Vlasenko552433b2009-04-04 19:29:21 +00004234 /* Do we need to flag set_local_var() errors?
4235 * "assignment to readonly var" and "putenv error"
4236 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004237 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004238 debug_leave();
4239 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004240 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00004241 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004242
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004243 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004244 if (0) {}
4245#if ENABLE_HUSH_BASH_COMPAT
4246 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004247 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4248 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004249#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004250#ifdef CMD_SINGLEWORD_NOGLOB_COND
4251 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4252 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4253
4254 }
4255#endif
4256 else {
4257 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4258 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004259
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004260 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004261 if (!argv_expanded[0]) {
Denys Vlasenko385cc592010-01-12 06:47:39 +01004262 free(argv_expanded);
Mike Frysinger28736c32009-10-18 01:11:45 -04004263 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004264 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004265 }
4266
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004267 x = find_builtin(argv_expanded[0]);
4268#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004269 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004270 if (!x)
4271 funcp = find_function(argv_expanded[0]);
4272#endif
4273 if (x || funcp) {
4274 if (!funcp) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01004275 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004276 debug_printf("exec with redirects only\n");
4277 rcode = setup_redirects(command, NULL);
4278 goto clean_up_and_ret1;
4279 }
Eric Andersen25f27032001-04-26 23:22:31 +00004280 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004281 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004282 * This is perfect for work that comes after exec().
4283 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004284 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004285 rcode = setup_redirects(command, squirrel);
4286 if (rcode == 0) {
4287 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004288 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004289 if (!funcp) {
4290 debug_printf_exec(": builtin '%s' '%s'...\n",
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004291 x->b_cmd, argv_expanded[1]);
Denys Vlasenko17323a62010-01-28 01:57:05 +01004292 rcode = x->b_function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004293 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004294 }
4295#if ENABLE_HUSH_FUNCTIONS
4296 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004297# if ENABLE_HUSH_LOCAL
4298 struct variable **sv;
4299 sv = G.shadowed_vars_pp;
4300 G.shadowed_vars_pp = &old_vars;
4301# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004302 debug_printf_exec(": function '%s' '%s'...\n",
4303 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004304 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004305# if ENABLE_HUSH_LOCAL
4306 G.shadowed_vars_pp = sv;
4307# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004308 }
4309#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004310 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004311#if ENABLE_FEATURE_SH_STANDALONE
4312 clean_up_and_ret:
4313#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004314 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004315 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004316 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004317 clean_up_and_ret1:
4318 free(argv_expanded);
4319 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004320 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004321 debug_printf_exec("run_pipe return %d\n", rcode);
4322 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004323 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004324
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004325#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004326 i = find_applet_by_name(argv_expanded[0]);
4327 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004328 rcode = setup_redirects(command, squirrel);
4329 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004330 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004331 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004332 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004333 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004334 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004335 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004336 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004337 }
4338#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00004339 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004340 }
4341
Denis Vlasenko552433b2009-04-04 19:29:21 +00004342 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004343 /* NB: argv_expanded may already be created, and that
4344 * might include `cmd` runs! Do not rerun it! We *must*
4345 * use argv_expanded if it's non-NULL */
4346
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004347 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004348 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004349 nextin = 0;
4350
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004351 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004352 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004353#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004354 volatile nommu_save_t nommu_save;
4355 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004356 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004357 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004358 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004359#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004360 command = &(pi->cmds[i]);
4361 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004362 debug_printf_exec(": pipe member '%s' '%s'...\n",
4363 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004364 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004365 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004366 }
Eric Andersen25f27032001-04-26 23:22:31 +00004367
4368 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004369 pipefds.rd = 0;
4370 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004371 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004372 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004373
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004374 command->pid = BB_MMU ? fork() : vfork();
4375 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004376#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004377 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004378 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004379
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004380 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004381 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004382 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004383 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004384 pgrp = pi->pgrp;
4385 if (pgrp < 0) /* true for 1st process only */
4386 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004387 if (setpgid(0, pgrp) == 0
4388 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004389 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004390 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004391 /* We do it in *every* child, not just first,
4392 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004393 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004394 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004395 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004396#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004397 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4398 /* 1st cmd in backgrounded pipe
4399 * should have its stdin /dev/null'ed */
4400 close(0);
4401 if (open(bb_dev_null, O_RDONLY))
4402 xopen("/", O_RDONLY);
4403 } else {
4404 xmove_fd(nextin, 0);
4405 }
4406 xmove_fd(pipefds.wr, 1);
4407 if (pipefds.rd > 1)
4408 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004409 /* Like bash, explicit redirects override pipes,
4410 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004411 if (setup_redirects(command, NULL))
4412 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004413
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004414 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004415 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4416
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004417 /* Stores to nommu_save list of env vars putenv'ed
4418 * (NOMMU, on MMU we don't need that) */
4419 /* cast away volatility... */
4420 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004421 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004422 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004423
Denis Vlasenkof9375282009-04-05 19:13:39 +00004424 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004425#if ENABLE_HUSH_FAST
4426 G.count_SIGCHLD++;
4427//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4428#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004429 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004430#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004431 /* Clean up after vforked child */
4432 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004433 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004434 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004435 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004436#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004437 free(argv_expanded);
4438 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004439 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004440 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00004441 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004442 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004443 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004444#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004445 /* Second and next children need to know pid of first one */
4446 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004447 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004448#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004449 }
Eric Andersen25f27032001-04-26 23:22:31 +00004450
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004451 if (i)
4452 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004453 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004454 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004455 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004456 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004457 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004458
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004459 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004460 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004461 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4462 return 1;
4463 }
4464
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004465 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004466 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004467 return -1;
4468}
4469
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004470#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004471static void debug_print_tree(struct pipe *pi, int lvl)
4472{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004473 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004474 [PIPE_SEQ] = "SEQ",
4475 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004476 [PIPE_OR ] = "OR" ,
4477 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004478 };
4479 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004480 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004481# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004482 [RES_IF ] = "IF" ,
4483 [RES_THEN ] = "THEN" ,
4484 [RES_ELIF ] = "ELIF" ,
4485 [RES_ELSE ] = "ELSE" ,
4486 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004487# endif
4488# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004489 [RES_FOR ] = "FOR" ,
4490 [RES_WHILE] = "WHILE",
4491 [RES_UNTIL] = "UNTIL",
4492 [RES_DO ] = "DO" ,
4493 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004494# endif
4495# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004496 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004497# endif
4498# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004499 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004500 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004501 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004502 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004503 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004504# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004505 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004506 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004507 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004508 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004509 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004510 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004511 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004512# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004513 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004514# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004515 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004516
4517 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004518
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004519 pin = 0;
4520 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004521 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4522 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004523 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004524 while (prn < pi->num_cmds) {
4525 struct command *command = &pi->cmds[prn];
4526 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004527
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004528 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004529 lvl*2, "", prn,
4530 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004531 if (command->group) {
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004532 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004533 CMDTYPE[command->cmd_type],
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004534 argv
4535#if !BB_MMU
4536 , " group_as_string:", command->group_as_string
4537#else
4538 , "", ""
4539#endif
4540 );
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004541 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004542 prn++;
4543 continue;
4544 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004545 if (argv) while (*argv) {
4546 fprintf(stderr, " '%s'", *argv);
4547 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004548 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004549 fprintf(stderr, "\n");
4550 prn++;
4551 }
4552 pi = pi->next;
4553 pin++;
4554 }
4555}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004556#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004557
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004558/* NB: called by pseudo_exec, and therefore must not modify any
4559 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004560static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004561{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004562#if ENABLE_HUSH_CASE
4563 char *case_word = NULL;
4564#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004565#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004566 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004567 char **for_lcur = NULL;
4568 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004569#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004570 smallint last_followup;
4571 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004572#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004573 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004574#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004575 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004576#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004577#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004578 smallint rword; /* enum reserved_style */
4579 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004580#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004581
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004582 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004583 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004584
Denis Vlasenko06810332007-05-21 23:30:54 +00004585#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004586 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004587 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4588 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004589 continue;
4590 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004591 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004592 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004593 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004594 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004595 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004596 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004597 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004598 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004599 continue;
4600 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004601 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4602 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004603 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004604 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004605 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004606 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004607 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004608 }
4609 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004610#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004611
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004612 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004613 * in order to return, no direct "return" statements please.
4614 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004615
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004616#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004617 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004618#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004619
Denis Vlasenko0e151382009-04-06 18:40:31 +00004620#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004621 rword = RES_NONE;
4622 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004623#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004624 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004625 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004626
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004627 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004628 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004629 if (G.flag_SIGINT)
4630 break;
4631
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004632 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004633 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4634 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004635#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004636 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004637 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004638 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004639 /* start of a loop: remember where loop starts */
4640 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004641 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004642 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004643#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004644 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004645 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004646 if ((rcode == 0 && last_followup == PIPE_OR)
4647 || (rcode != 0 && last_followup == PIPE_AND)
4648 ) {
4649 /* It is "<true> || CMD" or "<false> && CMD"
4650 * and we should not execute CMD */
4651 debug_printf_exec("skipped cmd because of || or &&\n");
4652 last_followup = pi->followup;
4653 continue;
4654 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004655 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004656 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004657 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004658#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004659 if (cond_code) {
4660 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004661 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004662 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004663 /* "if <false> THEN cmd": skip cmd */
4664 continue;
4665 }
4666 } else {
4667 if (rword == RES_ELSE || rword == RES_ELIF) {
4668 /* "if <true> then ... ELSE/ELIF cmd":
4669 * skip cmd and all following ones */
4670 break;
4671 }
4672 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004673#endif
4674#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004675 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004676 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004677 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004678
4679 static const char encoded_dollar_at[] ALIGN1 = {
4680 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4681 }; /* encoded representation of "$@" */
4682 static const char *const encoded_dollar_at_argv[] = {
4683 encoded_dollar_at, NULL
4684 }; /* argv list with one element: "$@" */
4685 char **vals;
4686
4687 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004688 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004689 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004690 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004691 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004692 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004693 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004694 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004695 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004696 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004697 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004698 debug_print_strings("for_list made from", vals);
4699 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004700 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004701 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004702 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004703 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004704 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004705 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004706 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004707 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004708 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004709 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004710 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004711 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004712 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004713 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004714 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004715 if (rword == RES_IN) {
4716 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4717 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004718 if (rword == RES_DONE) {
4719 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004720 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004721#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004722#if ENABLE_HUSH_CASE
4723 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004724 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004725 continue;
4726 }
4727 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004728 char **argv;
4729
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004730 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4731 break;
4732 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004733 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004734 while (*argv) {
4735 char *pattern = expand_string_to_string(*argv);
4736 /* TODO: which FNM_xxx flags to use? */
4737 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4738 free(pattern);
4739 if (cond_code == 0) { /* match! we will execute this branch */
4740 free(case_word); /* make future "word)" stop */
4741 case_word = NULL;
4742 break;
4743 }
4744 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004745 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004746 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004747 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004748 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004749 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004750 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004751 }
4752#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004753 /* Just pressing <enter> in shell should check for jobs.
4754 * OTOH, in non-interactive shell this is useless
4755 * and only leads to extra job checks */
4756 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004757 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004758 goto check_jobs_and_continue;
4759 continue;
4760 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004761
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004762 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004763 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004764 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004765 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004766 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004767 {
4768 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004769#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004770 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004771#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004772 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4773 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004774 /* We ran a builtin, function, or group.
4775 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004776 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004777 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004778 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004779 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004780#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004781 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004782 if (G.flag_break_continue) {
4783 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004784 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004785 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004786 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004787 G.depth_break_continue--;
4788 if (G.depth_break_continue == 0)
4789 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004790 /* else: e.g. "continue 2" should *break* once, *then* continue */
4791 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004792 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004793 goto check_jobs_and_break;
4794 /* "continue": simulate end of loop */
4795 rword = RES_DONE;
4796 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004797 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004798#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004799#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004800 if (G.flag_return_in_progress == 1) {
4801 /* same as "goto check_jobs_and_break" */
4802 checkjobs(NULL);
4803 break;
4804 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004805#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004806 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004807 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004808 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004809 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4810 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004811 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004812#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004813 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004814 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004815#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004816 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004817 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004818 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004819#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004820 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004821 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004822 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004823 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004824 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004825 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004826#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004827 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004828 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004829 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004830 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004831 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004832 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004833 }
4834 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004835
4836 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004837#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004838 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004839 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004840#endif
4841#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004842 /* Beware of "while false; true; do ..."! */
4843 if (pi->next && pi->next->res_word == RES_DO) {
4844 if (rword == RES_WHILE) {
4845 if (rcode) {
4846 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004847 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004848 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4849 goto check_jobs_and_break;
4850 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004851 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004852 if (rword == RES_UNTIL) {
4853 if (!rcode) {
4854 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004855 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004856 checkjobs(NULL);
4857 break;
4858 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004859 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004860 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004861#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004862
4863 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004864 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004865 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004866
4867#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004868 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004869#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004870#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004871 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004872 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004873 free(for_list);
4874#endif
4875#if ENABLE_HUSH_CASE
4876 free(case_word);
4877#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004878 debug_leave();
4879 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004880 return rcode;
4881}
4882
Eric Andersen25f27032001-04-26 23:22:31 +00004883/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004884static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004885{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004886 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004887 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004888 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004889 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004890 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004891 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004892 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004893 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004894 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004895 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004896 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004897 return rcode;
4898}
4899
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004900
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004901static struct pipe *new_pipe(void)
4902{
Eric Andersen25f27032001-04-26 23:22:31 +00004903 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004904 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004905 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004906 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004907 return pi;
4908}
4909
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004910/* Command (member of a pipe) is complete, or we start a new pipe
4911 * if ctx->command is NULL.
4912 * No errors possible here.
4913 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004914static int done_command(struct parse_context *ctx)
4915{
4916 /* The command is really already in the pipe structure, so
4917 * advance the pipe counter and make a new, null command. */
4918 struct pipe *pi = ctx->pipe;
4919 struct command *command = ctx->command;
4920
4921 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004922 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004923 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004924 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004925 }
4926 pi->num_cmds++;
4927 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004928 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004929 } else {
4930 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4931 }
4932
4933 /* Only real trickiness here is that the uncommitted
4934 * command structure is not counted in pi->num_cmds. */
4935 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004936 ctx->command = command = &pi->cmds[pi->num_cmds];
4937 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004938 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004939 return pi->num_cmds; /* used only for 0/nonzero check */
4940}
4941
4942static void done_pipe(struct parse_context *ctx, pipe_style type)
4943{
4944 int not_null;
4945
4946 debug_printf_parse("done_pipe entered, followup %d\n", type);
4947 /* Close previous command */
4948 not_null = done_command(ctx);
4949 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004950#if HAS_KEYWORDS
4951 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4952 ctx->ctx_inverted = 0;
4953 ctx->pipe->res_word = ctx->ctx_res_w;
4954#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004955
4956 /* Without this check, even just <enter> on command line generates
4957 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004958 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004959 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004960#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004961 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004962#endif
4963#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004964 || ctx->ctx_res_w == RES_DONE
4965 || ctx->ctx_res_w == RES_FOR
4966 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004967#endif
4968#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004969 || ctx->ctx_res_w == RES_ESAC
4970#endif
4971 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004972 struct pipe *new_p;
4973 debug_printf_parse("done_pipe: adding new pipe: "
4974 "not_null:%d ctx->ctx_res_w:%d\n",
4975 not_null, ctx->ctx_res_w);
4976 new_p = new_pipe();
4977 ctx->pipe->next = new_p;
4978 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004979 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004980 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004981 * This is used to control execution.
4982 * RES_FOR and RES_IN are NOT sticky (needed to support
4983 * cases where variable or value happens to match a keyword):
4984 */
4985#if ENABLE_HUSH_LOOPS
4986 if (ctx->ctx_res_w == RES_FOR
4987 || ctx->ctx_res_w == RES_IN)
4988 ctx->ctx_res_w = RES_NONE;
4989#endif
4990#if ENABLE_HUSH_CASE
4991 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004992 ctx->ctx_res_w = RES_CASE_BODY;
4993 if (ctx->ctx_res_w == RES_CASE)
4994 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004995#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004996 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004997 /* Create the memory for command, roughly:
4998 * ctx->pipe->cmds = new struct command;
4999 * ctx->command = &ctx->pipe->cmds[0];
5000 */
5001 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005002 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005003 }
5004 debug_printf_parse("done_pipe return\n");
5005}
5006
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005007static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005008{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005009 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00005010 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005011 /* Create the memory for command, roughly:
5012 * ctx->pipe->cmds = new struct command;
5013 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005014 */
5015 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005016}
5017
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005018/* If a reserved word is found and processed, parse context is modified
5019 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00005020 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005021#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005022struct reserved_combo {
5023 char literal[6];
5024 unsigned char res;
5025 unsigned char assignment_flag;
5026 int flag;
5027};
5028enum {
5029 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005030# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005031 FLAG_IF = (1 << RES_IF ),
5032 FLAG_THEN = (1 << RES_THEN ),
5033 FLAG_ELIF = (1 << RES_ELIF ),
5034 FLAG_ELSE = (1 << RES_ELSE ),
5035 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005036# endif
5037# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005038 FLAG_FOR = (1 << RES_FOR ),
5039 FLAG_WHILE = (1 << RES_WHILE),
5040 FLAG_UNTIL = (1 << RES_UNTIL),
5041 FLAG_DO = (1 << RES_DO ),
5042 FLAG_DONE = (1 << RES_DONE ),
5043 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005044# endif
5045# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005046 FLAG_MATCH = (1 << RES_MATCH),
5047 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005048# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005049 FLAG_START = (1 << RES_XXXX ),
5050};
5051
5052static const struct reserved_combo* match_reserved_word(o_string *word)
5053{
Eric Andersen25f27032001-04-26 23:22:31 +00005054 /* Mostly a list of accepted follow-up reserved words.
5055 * FLAG_END means we are done with the sequence, and are ready
5056 * to turn the compound list into a command.
5057 * FLAG_START means the word must start a new compound list.
5058 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005059 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005060# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005061 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5062 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5063 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5064 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5065 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5066 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005067# endif
5068# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005069 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5070 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5071 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5072 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5073 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5074 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005075# endif
5076# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005077 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5078 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005079# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005080 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005081 const struct reserved_combo *r;
5082
5083 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5084 if (strcmp(word->data, r->literal) == 0)
5085 return r;
5086 }
5087 return NULL;
5088}
Denis Vlasenkobb929512009-04-16 10:59:40 +00005089/* Return 0: not a keyword, 1: keyword
5090 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005091static int reserved_word(o_string *word, struct parse_context *ctx)
5092{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005093# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005094 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005095 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005096 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005097# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005098 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005099
Denis Vlasenkobb929512009-04-16 10:59:40 +00005100 if (word->o_quoted)
5101 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005102 r = match_reserved_word(word);
5103 if (!r)
5104 return 0;
5105
5106 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005107# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005108 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5109 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005110 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005111 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005112# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005113 if (r->flag == 0) { /* '!' */
5114 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005115 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00005116 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00005117 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005118 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005119 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005120 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005121 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005122 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005123
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005124 old = xmalloc(sizeof(*old));
5125 debug_printf_parse("push stack %p\n", old);
5126 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005127 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005128 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005129 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005130 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005131 ctx->ctx_res_w = RES_SNTX;
5132 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005133 } else {
5134 /* "{...} fi" is ok. "{...} if" is not
5135 * Example:
5136 * if { echo foo; } then { echo bar; } fi */
5137 if (ctx->command->group)
5138 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005139 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00005140
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005141 ctx->ctx_res_w = r->res;
5142 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005143 word->o_assignment = r->assignment_flag;
5144
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005145 if (ctx->old_flag & FLAG_END) {
5146 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005147
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005148 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005149 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005150 old = ctx->stack;
5151 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005152 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005153# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005154 o_addstr(&old->as_string, ctx->as_string.data);
5155 o_free_unsafe(&ctx->as_string);
5156 old->command->group_as_string = xstrdup(old->as_string.data);
5157 debug_printf_parse("pop, remembering as:'%s'\n",
5158 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005159# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005160 *ctx = *old; /* physical copy */
5161 free(old);
5162 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005163 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005164}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005165#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00005166
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005167/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005168 * Normal return is 0. Syntax errors return 1.
5169 * Note: on return, word is reset, but not o_free'd!
5170 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005171static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005172{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005173 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00005174
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005175 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005176 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005177 debug_printf_parse("done_word return 0: true null, ignored\n");
5178 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005179 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005180
Eric Andersen25f27032001-04-26 23:22:31 +00005181 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005182 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5183 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005184 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5185 * "2.7 Redirection
5186 * ...the word that follows the redirection operator
5187 * shall be subjected to tilde expansion, parameter expansion,
5188 * command substitution, arithmetic expansion, and quote
5189 * removal. Pathname expansion shall not be performed
5190 * on the word by a non-interactive shell; an interactive
5191 * shell may perform it, but shall do so only when
5192 * the expansion would result in one word."
5193 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005194 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005195 /* Cater for >\file case:
5196 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5197 * Same with heredocs:
5198 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5199 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005200 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5201 unbackslash(ctx->pending_redirect->rd_filename);
5202 /* Is it <<"HEREDOC"? */
5203 if (word->o_quoted) {
5204 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5205 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005206 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005207 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005208 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00005209 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005210 /* If this word wasn't an assignment, next ones definitely
5211 * can't be assignments. Even if they look like ones. */
5212 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5213 && word->o_assignment != WORD_IS_KEYWORD
5214 ) {
5215 word->o_assignment = NOT_ASSIGNMENT;
5216 } else {
5217 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5218 command->assignment_cnt++;
5219 word->o_assignment = MAYBE_ASSIGNMENT;
5220 }
5221
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005222#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005223# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00005224 if (ctx->ctx_dsemicolon
5225 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5226 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00005227 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005228 /* ctx->ctx_res_w = RES_MATCH; */
5229 ctx->ctx_dsemicolon = 0;
5230 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005231# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005232 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005233# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005234 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5235 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005236# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005237# if ENABLE_HUSH_CASE
5238 && ctx->ctx_res_w != RES_CASE
5239# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005240 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005241 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005242 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005243 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005244 debug_printf_parse("done_word return %d\n",
5245 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005246 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005247 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005248# ifdef CMD_SINGLEWORD_NOGLOB_COND
5249 if (strcmp(word->data, "export") == 0
5250# if ENABLE_HUSH_LOCAL
5251 || strcmp(word->data, "local") == 0
5252# endif
5253 ) {
5254 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5255 } else
5256# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005257# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005258 if (strcmp(word->data, "[[") == 0) {
5259 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5260 }
5261 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005262# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005263 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005264#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005265 if (command->group) {
5266 /* "{ echo foo; } echo bar" - bad */
5267 syntax_error_at(word->data);
5268 debug_printf_parse("done_word return 1: syntax error, "
5269 "groups and arglists don't mix\n");
5270 return 1;
5271 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005272 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005273 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5274 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005275 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005276 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005277 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005278 char *p = word->data;
5279 while (p[0] == SPECIAL_VAR_SYMBOL
5280 && (p[1] & 0x7f) == '@'
5281 && p[2] == SPECIAL_VAR_SYMBOL
5282 ) {
5283 p += 3;
5284 }
5285 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005286 /* saw no "$@", or not only "$@" but some
5287 * real text is there too */
5288 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005289 * e.g. "", $empty"" etc to not disappear */
5290 o_addchr(word, SPECIAL_VAR_SYMBOL);
5291 o_addchr(word, SPECIAL_VAR_SYMBOL);
5292 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005293 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005294 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005295 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005296 }
Eric Andersen25f27032001-04-26 23:22:31 +00005297
Denis Vlasenko06810332007-05-21 23:30:54 +00005298#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005299 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005300 if (word->o_quoted
5301 || !is_well_formed_var_name(command->argv[0], '\0')
5302 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005303 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005304 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005305 return 1;
5306 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005307 /* Force FOR to have just one word (variable name) */
5308 /* NB: basically, this makes hush see "for v in ..."
5309 * syntax as if it is "for v; in ...". FOR and IN become
5310 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005311 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005312 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005313#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005314#if ENABLE_HUSH_CASE
5315 /* Force CASE to have just one word */
5316 if (ctx->ctx_res_w == RES_CASE) {
5317 done_pipe(ctx, PIPE_SEQ);
5318 }
5319#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005320
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005321 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005322
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005323 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005324 return 0;
5325}
5326
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005327
5328/* Peek ahead in the input to find out if we have a "&n" construct,
5329 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005330 * Return:
5331 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5332 * REDIRFD_SYNTAX_ERR if syntax error,
5333 * REDIRFD_TO_FILE if no & was seen,
5334 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005335 */
5336#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005337#define parse_redir_right_fd(as_string, input) \
5338 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005339#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005340static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005341{
5342 int ch, d, ok;
5343
5344 ch = i_peek(input);
5345 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005346 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005347
5348 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005349 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005350 ch = i_peek(input);
5351 if (ch == '-') {
5352 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005353 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005354 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005355 }
5356 d = 0;
5357 ok = 0;
5358 while (ch != EOF && isdigit(ch)) {
5359 d = d*10 + (ch-'0');
5360 ok = 1;
5361 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005362 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005363 ch = i_peek(input);
5364 }
5365 if (ok) return d;
5366
5367//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5368
5369 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005370 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005371}
5372
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005373/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005374 */
5375static int parse_redirect(struct parse_context *ctx,
5376 int fd,
5377 redir_type style,
5378 struct in_str *input)
5379{
5380 struct command *command = ctx->command;
5381 struct redir_struct *redir;
5382 struct redir_struct **redirp;
5383 int dup_num;
5384
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005385 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005386 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005387 /* Check for a '>&1' type redirect */
5388 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5389 if (dup_num == REDIRFD_SYNTAX_ERR)
5390 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005391 } else {
5392 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005393 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005394 if (dup_num) { /* <<-... */
5395 ch = i_getch(input);
5396 nommu_addchr(&ctx->as_string, ch);
5397 ch = i_peek(input);
5398 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005399 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005400
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005401 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005402 int ch = i_peek(input);
5403 if (ch == '|') {
5404 /* >|FILE redirect ("clobbering" >).
5405 * Since we do not support "set -o noclobber" yet,
5406 * >| and > are the same for now. Just eat |.
5407 */
5408 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005409 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005410 }
5411 }
5412
5413 /* Create a new redir_struct and append it to the linked list */
5414 redirp = &command->redirects;
5415 while ((redir = *redirp) != NULL) {
5416 redirp = &(redir->next);
5417 }
5418 *redirp = redir = xzalloc(sizeof(*redir));
5419 /* redir->next = NULL; */
5420 /* redir->rd_filename = NULL; */
5421 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005422 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005423
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005424 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5425 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005426
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005427 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005428 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005429 /* Erik had a check here that the file descriptor in question
5430 * is legit; I postpone that to "run time"
5431 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005432 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5433 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005434 } else {
5435 /* Set ctx->pending_redirect, so we know what to do at the
5436 * end of the next parsed word. */
5437 ctx->pending_redirect = redir;
5438 }
5439 return 0;
5440}
5441
Eric Andersen25f27032001-04-26 23:22:31 +00005442/* If a redirect is immediately preceded by a number, that number is
5443 * supposed to tell which file descriptor to redirect. This routine
5444 * looks for such preceding numbers. In an ideal world this routine
5445 * needs to handle all the following classes of redirects...
5446 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5447 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5448 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5449 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005450 *
5451 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5452 * "2.7 Redirection
5453 * ... If n is quoted, the number shall not be recognized as part of
5454 * the redirection expression. For example:
5455 * echo \2>a
5456 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005457 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005458 *
5459 * A -1 return means no valid number was found,
5460 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005461 */
5462static int redirect_opt_num(o_string *o)
5463{
5464 int num;
5465
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005466 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005467 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005468 num = bb_strtou(o->data, NULL, 10);
5469 if (errno || num < 0)
5470 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005471 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005472 return num;
5473}
5474
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005475#if BB_MMU
5476#define fetch_till_str(as_string, input, word, skip_tabs) \
5477 fetch_till_str(input, word, skip_tabs)
5478#endif
5479static char *fetch_till_str(o_string *as_string,
5480 struct in_str *input,
5481 const char *word,
5482 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005483{
5484 o_string heredoc = NULL_O_STRING;
5485 int past_EOL = 0;
5486 int ch;
5487
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005488 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005489 while (1) {
5490 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005491 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005492 if (ch == '\n') {
5493 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5494 heredoc.data[past_EOL] = '\0';
5495 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5496 return heredoc.data;
5497 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005498 do {
5499 o_addchr(&heredoc, ch);
5500 past_EOL = heredoc.length;
5501 jump_in:
5502 do {
5503 ch = i_getch(input);
5504 nommu_addchr(as_string, ch);
5505 } while (skip_tabs && ch == '\t');
5506 } while (ch == '\n');
5507 }
5508 if (ch == EOF) {
5509 o_free_unsafe(&heredoc);
5510 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005511 }
5512 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005513 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005514 }
5515}
5516
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005517/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5518 * and load them all. There should be exactly heredoc_cnt of them.
5519 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005520static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5521{
5522 struct pipe *pi = ctx->list_head;
5523
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005524 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005525 int i;
5526 struct command *cmd = pi->cmds;
5527
5528 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5529 pi->num_cmds,
5530 cmd->argv ? cmd->argv[0] : "NONE");
5531 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005532 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005533
5534 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5535 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005536 while (redir) {
5537 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005538 char *p;
5539
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005540 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005541 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005542 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005543 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005544 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005545 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005546 return 1;
5547 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005548 free(redir->rd_filename);
5549 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005550 heredoc_cnt--;
5551 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005552 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005553 }
5554 cmd++;
5555 }
5556 pi = pi->next;
5557 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005558#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005559 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005560 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005561 bb_error_msg_and_die("heredoc BUG 2");
5562#endif
5563 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005564}
5565
5566
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005567#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005568static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005569{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005570 pid_t pid;
5571 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005572# if !BB_MMU
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01005573 char **to_free = NULL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005574# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005575
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005576 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00005577 pid = BB_MMU ? fork() : vfork();
5578 if (pid < 0)
5579 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005580
Denis Vlasenko05743d72008-02-10 12:10:08 +00005581 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005582 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005583 /* Process substitution is not considered to be usual
5584 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005585 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5586 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005587 bb_signals(0
5588 + (1 << SIGTSTP)
5589 + (1 << SIGTTIN)
5590 + (1 << SIGTTOU)
5591 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005592 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005593 close(channel[0]); /* NB: close _first_, then move fd! */
5594 xmove_fd(channel[1], 1);
5595 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005596 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005597 /* Awful hack for `trap` or $(trap).
5598 *
5599 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5600 * contains an example where "trap" is executed in a subshell:
5601 *
5602 * save_traps=$(trap)
5603 * ...
5604 * eval "$save_traps"
5605 *
5606 * Standard does not say that "trap" in subshell shall print
5607 * parent shell's traps. It only says that its output
5608 * must have suitable form, but then, in the above example
5609 * (which is not supposed to be normative), it implies that.
5610 *
5611 * bash (and probably other shell) does implement it
5612 * (traps are reset to defaults, but "trap" still shows them),
5613 * but as a result, "trap" logic is hopelessly messed up:
5614 *
5615 * # trap
5616 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5617 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5618 * # true | trap <--- trap is in subshell - no output (ditto)
5619 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5620 * trap -- 'echo Ho' SIGWINCH
5621 * # echo `(trap)` <--- in subshell in subshell - output
5622 * trap -- 'echo Ho' SIGWINCH
5623 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5624 * trap -- 'echo Ho' SIGWINCH
5625 *
5626 * The rules when to forget and when to not forget traps
5627 * get really complex and nonsensical.
5628 *
5629 * Our solution: ONLY bare $(trap) or `trap` is special.
5630 */
5631 s = skip_whitespace(s);
5632 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5633 {
5634 static const char *const argv[] = { NULL, NULL };
5635 builtin_trap((char**)argv);
5636 exit(0); /* not _exit() - we need to fflush */
5637 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005638# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005639 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005640 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005641 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005642# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005643 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005644 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5645 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005646 * echo OK
5647 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005648 re_execute_shell(&to_free,
5649 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005650 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005651 G.global_argv + 1,
5652 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005653# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005654 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005655
5656 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005657 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005658# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005659 G.count_SIGCHLD++;
5660//bb_error_msg("[%d] fork in generate_stream_from_string: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005661# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005662 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005663# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005664 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005665# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005666 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005667 close_on_exec_on(channel[0]);
5668 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005669}
5670
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005671/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005672static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005673{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005674 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005675 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005676 pid_t pid;
5677 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005678
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005679 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005680
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005681 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005682 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005683 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005684 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005685 if (ch == '\n') {
5686 eol_cnt++;
5687 continue;
5688 }
5689 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005690 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005691 eol_cnt--;
5692 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005693 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005694 }
5695
Denys Vlasenko647553a2009-11-15 19:58:19 +01005696 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005697 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005698 /* We need to extract exitcode. Test case
5699 * "true; echo `sleep 1; false` $?"
5700 * should print 1 */
5701 safe_waitpid(pid, &status, 0);
5702 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5703 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005704}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005705#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005706
Denys Vlasenkoc2704542009-11-20 19:14:19 +01005707#if !ENABLE_HUSH_FUNCTIONS
5708#define parse_group(dest, ctx, input, ch) \
5709 parse_group(ctx, input, ch)
5710#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005711static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005712 struct in_str *input, int ch)
5713{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005714 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005715 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005716 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005717 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005718 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005719 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005720
5721 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005722#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005723 if (ch == '(' && !dest->o_quoted) {
5724 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005725 if (done_word(dest, ctx))
5726 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005727 if (!command->argv)
5728 goto skip; /* (... */
5729 if (command->argv[1]) { /* word word ... (... */
5730 syntax_error_unexpected_ch('(');
5731 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005732 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005733 /* it is "word(..." or "word (..." */
5734 do
5735 ch = i_getch(input);
5736 while (ch == ' ' || ch == '\t');
5737 if (ch != ')') {
5738 syntax_error_unexpected_ch(ch);
5739 return 1;
5740 }
5741 nommu_addchr(&ctx->as_string, ch);
5742 do
5743 ch = i_getch(input);
5744 while (ch == ' ' || ch == '\t' || ch == '\n');
5745 if (ch != '{') {
5746 syntax_error_unexpected_ch(ch);
5747 return 1;
5748 }
5749 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005750 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005751 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005752 }
5753#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005754
5755#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005756 if (command->argv /* word [word]{... */
5757 || dest->length /* word{... */
5758 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005759 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005760 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005761 debug_printf_parse("parse_group return 1: "
5762 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005763 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005764 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005765#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005766
5767#if ENABLE_HUSH_FUNCTIONS
5768 skip:
5769#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005770 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005771 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005772 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005773 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005774 } else {
5775 /* bash does not allow "{echo...", requires whitespace */
5776 ch = i_getch(input);
5777 if (ch != ' ' && ch != '\t' && ch != '\n') {
5778 syntax_error_unexpected_ch(ch);
5779 return 1;
5780 }
5781 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005782 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005783
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005784 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005785#if BB_MMU
5786# define as_string NULL
5787#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005788 char *as_string = NULL;
5789#endif
5790 pipe_list = parse_stream(&as_string, input, endch);
5791#if !BB_MMU
5792 if (as_string)
5793 o_addstr(&ctx->as_string, as_string);
5794#endif
5795 /* empty ()/{} or parse error? */
5796 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005797 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005798 if (!BB_MMU)
5799 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005800 debug_printf_parse("parse_group return 1: "
5801 "parse_stream returned %p\n", pipe_list);
5802 return 1;
5803 }
5804 command->group = pipe_list;
5805#if !BB_MMU
5806 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5807 command->group_as_string = as_string;
5808 debug_printf_parse("end of group, remembering as:'%s'\n",
5809 command->group_as_string);
5810#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005811#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005812 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005813 debug_printf_parse("parse_group return 0\n");
5814 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005815 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005816}
5817
Mike Frysinger98c52642009-04-02 10:02:37 +00005818#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005819/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005820static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005821/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005822static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005823{
5824 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005825 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005826 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005827 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005828 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005829 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005830 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005831 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005832 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005833 }
5834}
5835/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005836static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005837{
5838 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005839 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005840 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005841 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005842 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005843 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005844 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005845 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005846 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005847 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005848 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005849 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005850 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005851 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005852 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005853 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005854 continue;
5855 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005856 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005857 }
5858}
5859/* Process `cmd` - copy contents until "`" is seen. Complicated by
5860 * \` quoting.
5861 * "Within the backquoted style of command substitution, backslash
5862 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5863 * The search for the matching backquote shall be satisfied by the first
5864 * backquote found without a preceding backslash; during this search,
5865 * if a non-escaped backquote is encountered within a shell comment,
5866 * a here-document, an embedded command substitution of the $(command)
5867 * form, or a quoted string, undefined results occur. A single-quoted
5868 * or double-quoted string that begins, but does not end, within the
5869 * "`...`" sequence produces undefined results."
5870 * Example Output
5871 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5872 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005873static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005874{
5875 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005876 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005877 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005878 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005879 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005880 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005881 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005882 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005883 if (ch == '\\') {
5884 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005885 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005886 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005887 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005888 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005889 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005890 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005891 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005892 ch = ch2;
5893 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005894 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005895 }
5896}
5897/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5898 * quoting and nested ()s.
5899 * "With the $(command) style of command substitution, all characters
5900 * following the open parenthesis to the matching closing parenthesis
5901 * constitute the command. Any valid shell script can be used for command,
5902 * except a script consisting solely of redirections which produces
5903 * unspecified results."
5904 * Example Output
5905 * echo $(echo '(TEST)' BEST) (TEST) BEST
5906 * echo $(echo 'TEST)' BEST) TEST) BEST
5907 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02005908 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005909 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005910 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005911 * In bash compat mode, it needs to also be able to stop on '}' or ':'
5912 * for ${var:N[:M]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005913 */
Denys Vlasenko74369502010-05-21 19:52:01 +02005914#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005915static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005916{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005917 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02005918 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005919#if ENABLE_HUSH_BASH_COMPAT
5920 char end_char2 = end_ch >> 8;
5921#endif
5922 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
5923
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005924 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005925 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005926 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005927 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005928 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005929 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005930 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005931 if (!dbl)
5932 break;
5933 /* we look for closing )) of $((EXPR)) */
5934 if (i_peek(input) == end_ch) {
5935 i_getch(input); /* eat second ')' */
5936 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00005937 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005938 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005939 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005940 if (ch == '(' || ch == '{') {
5941 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005942 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005943 o_addchr(dest, ch);
5944 continue;
5945 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005946 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005947 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005948 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005949 continue;
5950 }
5951 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005952 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005953 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005954 continue;
5955 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005956 if (ch == '`') {
5957 add_till_backquote(dest, input);
5958 o_addchr(dest, ch);
5959 continue;
5960 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005961 if (ch == '\\') {
5962 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005963 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005964 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005965 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005966 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005967 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005968 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005969 continue;
5970 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005971 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005972 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005973}
Mike Frysinger98c52642009-04-02 10:02:37 +00005974#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005975
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005976/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005977#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005978#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005979 handle_dollar(dest, input)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005980#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005981#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005982static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005983 o_string *dest,
5984 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005985{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005986 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005987 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005988
5989 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005990 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005991 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005992 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005993 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005994 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005995 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005996 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005997 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005998 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005999 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006000 if (!isalnum(ch) && ch != '_')
6001 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006002 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006003 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006004 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006005 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006006 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006007 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006008 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006009 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006010 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006011 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006012 o_addchr(dest, ch | quote_mask);
6013 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006014 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006015 case '$': /* pid */
6016 case '!': /* last bg pid */
6017 case '?': /* last exit code */
6018 case '#': /* number of args */
6019 case '*': /* args */
6020 case '@': /* args */
6021 goto make_one_char_var;
6022 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04006023 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6024
Denys Vlasenko74369502010-05-21 19:52:01 +02006025 ch = i_getch(input); /* eat '{' */
6026 nommu_addchr(as_string, ch);
6027
6028 ch = i_getch(input); /* first char after '{' */
6029 nommu_addchr(as_string, ch);
6030 /* It should be ${?}, or ${#var},
6031 * or even ${?+subst} - operator acting on a special variable,
6032 * or the beginning of variable name.
6033 */
6034 if (!strchr("$!?#*@_", ch) && !isalnum(ch)) { /* not one of those */
6035 bad_dollar_syntax:
6036 syntax_error_unterm_str("${name}");
6037 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
6038 return 1;
6039 }
6040 ch |= quote_mask;
6041
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006042 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02006043 * However, this regresses some of our testsuite cases
6044 * which check invalid constructs like ${%}.
6045 * Oh well... let's check that the var name part is fine... */
6046
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006047 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006048 unsigned pos;
6049
Denys Vlasenko74369502010-05-21 19:52:01 +02006050 o_addchr(dest, ch);
6051 debug_printf_parse(": '%c'\n", ch);
6052
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006053 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006054 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02006055 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00006056 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006057
Denys Vlasenko74369502010-05-21 19:52:01 +02006058 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006059 unsigned end_ch;
6060 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006061 /* handle parameter expansions
6062 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6063 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006064 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6065 goto bad_dollar_syntax;
Denys Vlasenko74369502010-05-21 19:52:01 +02006066 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006067
6068 /* Eat everything until closing '}' (or ':') */
6069 end_ch = '}';
6070 if (ENABLE_HUSH_BASH_COMPAT
6071 && ch == ':'
6072 && !strchr("%#:-=+?"+3, i_peek(input))
6073 ) {
6074 /* It's ${var:N[:M]} thing */
6075 end_ch = '}' * 0x100 + ':';
6076 }
6077 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006078 if (!BB_MMU)
6079 pos = dest->length;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006080 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006081 if (as_string) {
6082 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006083 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006084 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006085
6086 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6087 /* close the first block: */
6088 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6089 /* while parsing N from ${var:N[:M]}... */
6090 if ((end_ch & 0xff) == last_ch) {
6091 /* ...got ':' - parse the rest */
6092 end_ch = '}';
6093 goto again;
6094 }
6095 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6096 o_addstr(dest, "999999999");
6097 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006098 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006099 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006100 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006101 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6102 break;
6103 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006104#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006105 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006106 unsigned pos;
6107
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006108 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006109 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006110# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006111 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006112 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006113 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006114 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6115 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006116 if (!BB_MMU)
6117 pos = dest->length;
6118 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
6119#if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006120 if (as_string) {
6121 o_addstr(as_string, dest->data + pos);
6122 o_addchr(as_string, ')');
6123 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006124 }
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006125#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006126 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006127 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006128 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006129# endif
6130# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006131 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6132 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006133 if (!BB_MMU)
6134 pos = dest->length;
6135 add_till_closing_bracket(dest, input, ')');
6136#if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006137 if (as_string) {
6138 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006139 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006140 }
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006141#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006142 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006143# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006144 break;
6145 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006146#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006147 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006148 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006149 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006150 ch = i_peek(input);
6151 if (isalnum(ch)) { /* it's $_name or $_123 */
6152 ch = '_';
6153 goto make_var;
6154 }
6155 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02006156 /* TODO: $_ and $-: */
6157 /* $_ Shell or shell script name; or last argument of last command
6158 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6159 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006160 /* $- Option flags set by set builtin or shell options (-i etc) */
6161 default:
6162 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00006163 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006164 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00006165 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006166#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00006167}
6168
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006169#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006170#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006171 parse_stream_dquoted(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006172#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006173#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006174static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006175 o_string *dest,
6176 struct in_str *input,
6177 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006178{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006179 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006180 int next;
6181
6182 again:
6183 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006184 if (ch != EOF)
6185 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006186 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006187 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006188 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006189 debug_printf_parse("parse_stream_dquoted return 0\n");
6190 return 0;
6191 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006192 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006193 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006194 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006195 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006196 }
6197 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006198 if (ch != '\n') {
6199 next = i_peek(input);
6200 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006201 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006202 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006203 if (ch == '\\') {
6204 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006205 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006206 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006207 }
6208 /* bash:
6209 * "The backslash retains its special meaning [in "..."]
6210 * only when followed by one of the following characters:
6211 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006212 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006213 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006214 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00006215 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006216 if (ch != '\n') {
6217 o_addqchr(dest, ch);
6218 nommu_addchr(as_string, ch);
6219 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006220 } else {
6221 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00006222 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006223 }
6224 goto again;
6225 }
6226 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006227 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006228 debug_printf_parse("parse_stream_dquoted return 1: "
6229 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006230 return 1;
6231 }
6232 goto again;
6233 }
6234#if ENABLE_HUSH_TICK
6235 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006236 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006237 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6238 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006239 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006240 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6241 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00006242 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006243 }
6244#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00006245 o_addQchr(dest, ch);
6246 if (ch == '='
6247 && (dest->o_assignment == MAYBE_ASSIGNMENT
6248 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006249 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00006250 ) {
6251 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6252 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006253 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006254#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006255}
6256
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006257/*
6258 * Scan input until EOF or end_trigger char.
6259 * Return a list of pipes to execute, or NULL on EOF
6260 * or if end_trigger character is met.
6261 * On syntax error, exit is shell is not interactive,
6262 * reset parsing machinery and start parsing anew,
6263 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006264 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006265static struct pipe *parse_stream(char **pstring,
6266 struct in_str *input,
6267 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006268{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006269 struct parse_context ctx;
6270 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006271 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006272 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006273
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006274 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006275 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006276 * found. When recursing, quote state is passed in via dest->o_escape.
6277 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006278 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006279 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006280 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006281
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006282 /* If very first arg is "" or '', dest.data may end up NULL.
6283 * Preventing this: */
6284 o_addchr(&dest, '\0');
6285 dest.length = 0;
6286
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006287 G.ifs = get_local_var_value("IFS");
6288 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01006289 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006290
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006291 reset:
6292#if ENABLE_HUSH_INTERACTIVE
6293 input->promptmode = 0; /* PS1 */
6294#endif
6295 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6296 initialize_context(&ctx);
6297 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006298 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006299 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006300 const char *is_ifs;
6301 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006302 int ch;
6303 int next;
6304 int redir_fd;
6305 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006306
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006307 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006308 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006309 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006310 goto parse_error;
6311 }
6312 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006313 is_in_dquote = 0;
6314 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006315 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006316 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6317 ch, ch, dest.o_escape);
6318 if (ch == EOF) {
6319 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006320
6321 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006322 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006323 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006324 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006325 /* end_trigger == '}' case errors out earlier,
6326 * checking only ')' */
6327 if (end_trigger == ')') {
6328 syntax_error_unterm_ch('('); /* exits */
6329 /* goto parse_error; */
6330 }
6331
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006332 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006333 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006334 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006335 o_free(&dest);
6336 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006337 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006338 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006339 /* (this makes bare "&" cmd a no-op.
6340 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006341 if (pi->num_cmds == 0
6342 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6343 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006344 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006345 pi = NULL;
6346 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006347#if !BB_MMU
6348 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6349 if (pstring)
6350 *pstring = ctx.as_string.data;
6351 else
6352 o_free_unsafe(&ctx.as_string);
6353#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006354 debug_leave();
6355 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006356 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006357 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006358 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006359
6360 next = '\0';
6361 if (ch != '\n')
6362 next = i_peek(input);
6363
6364 is_special = "{}<>;&|()#'" /* special outside of "str" */
6365 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6366 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02006367 if (ctx.command->argv /* word [word]{... - non-special */
6368 || dest.length /* word{... - non-special */
6369 || dest.o_quoted /* ""{... - non-special */
6370 || (next != ';' /* }; - special */
6371 && next != ')' /* }) - special */
6372 && next != '&' /* }& and }&& ... - special */
6373 && next != '|' /* }|| ... - special */
6374 && !strchr(G.ifs, next) /* {word - non-special */
6375 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006376 ) {
6377 /* They are not special, skip "{}" */
6378 is_special += 2;
6379 }
6380 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006381 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006382
6383 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006384 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006385 o_addQchr(&dest, ch);
6386 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6387 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006388 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006389 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006390 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006391 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006392 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006393 continue;
6394 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006395
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006396 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006397 if (done_word(&dest, &ctx)) {
6398 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006399 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006400 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006401#if ENABLE_HUSH_CASE
6402 /* "case ... in <newline> word) ..." -
6403 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006404 if (ctx.command->argv == NULL
6405 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006406 ) {
6407 continue;
6408 }
6409#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006410 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006411 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006412 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6413 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006414 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006415 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006416 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006417 heredoc_cnt = 0;
6418 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006419 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006420 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006421 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006422 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006423 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006424 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006425
6426 /* "cmd}" or "cmd }..." without semicolon or &:
6427 * } is an ordinary char in this case, even inside { cmd; }
6428 * Pathological example: { ""}; } should exec "}" cmd
6429 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006430 if (ch == '}') {
6431 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6432 || dest.length != 0 /* word} */
6433 || dest.o_quoted /* ""} */
6434 ) {
6435 goto ordinary_char;
6436 }
6437 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6438 goto skip_end_trigger;
6439 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006440 }
6441
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006442 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006443 && (ch != ';' || heredoc_cnt == 0)
6444#if ENABLE_HUSH_CASE
6445 && (ch != ')'
6446 || ctx.ctx_res_w != RES_MATCH
6447 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6448 )
6449#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006450 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006451 if (heredoc_cnt) {
6452 /* This is technically valid:
6453 * { cat <<HERE; }; echo Ok
6454 * heredoc
6455 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006456 * HERE
6457 * but we don't support this.
6458 * We require heredoc to be in enclosing {}/(),
6459 * if any.
6460 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006461 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006462 goto parse_error;
6463 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006464 if (done_word(&dest, &ctx)) {
6465 goto parse_error;
6466 }
6467 done_pipe(&ctx, PIPE_SEQ);
6468 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006469 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006470 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006471 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006472 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006473 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006474#if !BB_MMU
6475 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6476 if (pstring)
6477 *pstring = ctx.as_string.data;
6478 else
6479 o_free_unsafe(&ctx.as_string);
6480#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006481 debug_leave();
6482 debug_printf_parse("parse_stream return %p: "
6483 "end_trigger char found\n",
6484 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006485 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006486 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006487 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006488 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006489 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006490 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006491
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006492 /* Catch <, > before deciding whether this word is
6493 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6494 switch (ch) {
6495 case '>':
6496 redir_fd = redirect_opt_num(&dest);
6497 if (done_word(&dest, &ctx)) {
6498 goto parse_error;
6499 }
6500 redir_style = REDIRECT_OVERWRITE;
6501 if (next == '>') {
6502 redir_style = REDIRECT_APPEND;
6503 ch = i_getch(input);
6504 nommu_addchr(&ctx.as_string, ch);
6505 }
6506#if 0
6507 else if (next == '(') {
6508 syntax_error(">(process) not supported");
6509 goto parse_error;
6510 }
6511#endif
6512 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6513 goto parse_error;
6514 continue; /* back to top of while (1) */
6515 case '<':
6516 redir_fd = redirect_opt_num(&dest);
6517 if (done_word(&dest, &ctx)) {
6518 goto parse_error;
6519 }
6520 redir_style = REDIRECT_INPUT;
6521 if (next == '<') {
6522 redir_style = REDIRECT_HEREDOC;
6523 heredoc_cnt++;
6524 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6525 ch = i_getch(input);
6526 nommu_addchr(&ctx.as_string, ch);
6527 } else if (next == '>') {
6528 redir_style = REDIRECT_IO;
6529 ch = i_getch(input);
6530 nommu_addchr(&ctx.as_string, ch);
6531 }
6532#if 0
6533 else if (next == '(') {
6534 syntax_error("<(process) not supported");
6535 goto parse_error;
6536 }
6537#endif
6538 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6539 goto parse_error;
6540 continue; /* back to top of while (1) */
6541 }
6542
6543 if (dest.o_assignment == MAYBE_ASSIGNMENT
6544 /* check that we are not in word in "a=1 2>word b=1": */
6545 && !ctx.pending_redirect
6546 ) {
6547 /* ch is a special char and thus this word
6548 * cannot be an assignment */
6549 dest.o_assignment = NOT_ASSIGNMENT;
6550 }
6551
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006552 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6553
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006554 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006555 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006556 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006557 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006558 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006559 if (ch == EOF || ch == '\n')
6560 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006561 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006562 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006563 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006564 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006565 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006566 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006567 }
6568 break;
6569 case '\\':
6570 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006571 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006572 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006573 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006574 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006575 if (ch != '\n') {
6576 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006577 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006578 o_addchr(&dest, ch);
6579 nommu_addchr(&ctx.as_string, ch);
6580 /* Example: echo Hello \2>file
6581 * we need to know that word 2 is quoted */
6582 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006583 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006584#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006585 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006586 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6587 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006588 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006589#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006590 break;
6591 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006592 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006593 debug_printf_parse("parse_stream parse error: "
6594 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006595 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006596 }
Eric Andersen25f27032001-04-26 23:22:31 +00006597 break;
6598 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006599 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006600 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006601 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006602 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006603 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006604 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006605 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006606 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006607 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006608 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006609 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006610 }
Eric Andersen25f27032001-04-26 23:22:31 +00006611 break;
6612 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006613 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006614 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006615 if (dest.o_assignment == NOT_ASSIGNMENT)
6616 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006617 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006618#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006619 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006620#if !BB_MMU
6621 int pos;
6622#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006623 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6624 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006625#if !BB_MMU
6626 pos = dest.length;
6627#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006628 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006629#if !BB_MMU
6630 o_addstr(&ctx.as_string, dest.data + pos);
6631 o_addchr(&ctx.as_string, '`');
6632#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006633 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6634 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006635 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006636 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006637#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006638 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006639#if ENABLE_HUSH_CASE
6640 case_semi:
6641#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006642 if (done_word(&dest, &ctx)) {
6643 goto parse_error;
6644 }
6645 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006646#if ENABLE_HUSH_CASE
6647 /* Eat multiple semicolons, detect
6648 * whether it means something special */
6649 while (1) {
6650 ch = i_peek(input);
6651 if (ch != ';')
6652 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006653 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006654 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006655 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006656 ctx.ctx_dsemicolon = 1;
6657 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006658 break;
6659 }
6660 }
6661#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006662 new_cmd:
6663 /* We just finished a cmd. New one may start
6664 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006665 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006666 break;
6667 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006668 if (done_word(&dest, &ctx)) {
6669 goto parse_error;
6670 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006671 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006672 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006673 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006674 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006675 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006676 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006677 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006678 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006679 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006680 if (done_word(&dest, &ctx)) {
6681 goto parse_error;
6682 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006683#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006684 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006685 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006686#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006687 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006688 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006689 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006690 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006691 } else {
6692 /* we could pick up a file descriptor choice here
6693 * with redirect_opt_num(), but bash doesn't do it.
6694 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006695 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006696#if !BB_MMU
6697 o_reset_to_empty_unquoted(&ctx.as_string);
6698#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006699 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006700 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006701 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006702#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006703 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006704 if (ctx.ctx_res_w == RES_MATCH
6705 && ctx.command->argv == NULL /* not (word|(... */
6706 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006707 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006708 ) {
6709 continue;
6710 }
6711#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006712 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006713 if (parse_group(&dest, &ctx, input, ch) != 0) {
6714 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006715 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006716 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006717 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006718#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006719 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006720 goto case_semi;
6721#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006722 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006723 /* proper use of this character is caught by end_trigger:
6724 * if we see {, we call parse_group(..., end_trigger='}')
6725 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006726 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006727 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006728 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006729 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006730 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006731 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006732 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006733
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006734 parse_error:
6735 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006736 struct parse_context *pctx;
6737 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006738
6739 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006740 * Sample for finding leaks on syntax error recovery path.
6741 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006742 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006743 * Samples to catch leaks at execution:
6744 * while if (true | {true;}); then echo ok; fi; do break; done
6745 * 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 +00006746 */
6747 pctx = &ctx;
6748 do {
6749 /* Update pipe/command counts,
6750 * otherwise freeing may miss some */
6751 done_pipe(pctx, PIPE_SEQ);
6752 debug_printf_clean("freeing list %p from ctx %p\n",
6753 pctx->list_head, pctx);
6754 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006755 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006756 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006757#if !BB_MMU
6758 o_free_unsafe(&pctx->as_string);
6759#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006760 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006761 if (pctx != &ctx) {
6762 free(pctx);
6763 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006764 IF_HAS_KEYWORDS(pctx = p2;)
6765 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006766 /* Free text, clear all dest fields */
6767 o_free(&dest);
6768 /* If we are not in top-level parse, we return,
6769 * our caller will propagate error.
6770 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006771 if (end_trigger != ';') {
6772#if !BB_MMU
6773 if (pstring)
6774 *pstring = NULL;
6775#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006776 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006777 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006778 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006779 /* Discard cached input, force prompt */
6780 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006781 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006782 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006783 }
Eric Andersen25f27032001-04-26 23:22:31 +00006784}
6785
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006786/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006787 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6788 * end_trigger controls how often we stop parsing
6789 * NUL: parse all, execute, return
6790 * ';': parse till ';' or newline, execute, repeat till EOF
6791 */
6792static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006793{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006794 /* Why we need empty flag?
6795 * An obscure corner case "false; ``; echo $?":
6796 * empty command in `` should still set $? to 0.
6797 * But we can't just set $? to 0 at the start,
6798 * this breaks "false; echo `echo $?`" case.
6799 */
6800 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006801 while (1) {
6802 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006803
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006804 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006805 if (!pipe_list) { /* EOF */
6806 if (empty)
6807 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006808 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006809 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006810 debug_print_tree(pipe_list, 0);
6811 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6812 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006813 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006814 }
Eric Andersen25f27032001-04-26 23:22:31 +00006815}
6816
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006817static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006818{
6819 struct in_str input;
6820 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006821 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006822}
6823
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006824static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006825{
Eric Andersen25f27032001-04-26 23:22:31 +00006826 struct in_str input;
6827 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006828 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006829}
6830
Denis Vlasenkof9375282009-04-05 19:13:39 +00006831/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006832static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006833{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006834 unsigned sig;
6835 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006836 sigset_t old_blocked_set;
6837
6838 if (!G.inherited_set_is_saved) {
6839 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6840 G.inherited_set = G.blocked_set;
6841 }
6842 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006843
Denis Vlasenkof9375282009-04-05 19:13:39 +00006844 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006845 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006846 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006847 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006848 mask |= SPECIAL_JOB_SIGS;
6849 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006850 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006851
Denis Vlasenkof9375282009-04-05 19:13:39 +00006852 sig = 0;
6853 while (mask) {
6854 if (mask & 1)
6855 sigaddset(&G.blocked_set, sig);
6856 mask >>= 1;
6857 sig++;
6858 }
6859 sigdelset(&G.blocked_set, SIGCHLD);
6860
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006861 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
6862 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6863
Denis Vlasenkof9375282009-04-05 19:13:39 +00006864 /* POSIX allows shell to re-enable SIGCHLD
6865 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006866#if ENABLE_HUSH_FAST
6867 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006868 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006869 signal(SIGCHLD, SIGCHLD_handler);
6870#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006871 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006872 signal(SIGCHLD, SIG_DFL);
6873#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006874
6875 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00006876}
6877
6878#if ENABLE_HUSH_JOB
6879/* helper */
6880static void maybe_set_to_sigexit(int sig)
6881{
6882 void (*handler)(int);
6883 /* non_DFL_mask'ed signals are, well, masked,
6884 * no need to set handler for them.
6885 */
6886 if (!((G.non_DFL_mask >> sig) & 1)) {
6887 handler = signal(sig, sigexit);
6888 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6889 signal(sig, handler);
6890 }
6891}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006892/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006893static void set_fatal_handlers(void)
6894{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006895 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006896 if (HUSH_DEBUG) {
6897 maybe_set_to_sigexit(SIGILL );
6898 maybe_set_to_sigexit(SIGFPE );
6899 maybe_set_to_sigexit(SIGBUS );
6900 maybe_set_to_sigexit(SIGSEGV);
6901 maybe_set_to_sigexit(SIGTRAP);
6902 } /* else: hush is perfect. what SEGV? */
6903 maybe_set_to_sigexit(SIGABRT);
6904 /* bash 3.2 seems to handle these just like 'fatal' ones */
6905 maybe_set_to_sigexit(SIGPIPE);
6906 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006907 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006908 * if we aren't interactive... but in this case
6909 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006910 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006911 /*maybe_set_to_sigexit(SIGTERM);*/
6912 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006913}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006914#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006915
Denis Vlasenkod5762932009-03-31 11:22:57 +00006916static int set_mode(const char cstate, const char mode)
6917{
6918 int state = (cstate == '-' ? 1 : 0);
6919 switch (mode) {
6920 case 'n': G.fake_mode = state; break;
6921 case 'x': /*G.debug_mode = state;*/ break;
6922 default: return EXIT_FAILURE;
6923 }
6924 return EXIT_SUCCESS;
6925}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006926
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006927int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006928int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006929{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006930 static const struct variable const_shell_ver = {
6931 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006932 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006933 .max_len = 1, /* 0 can provoke free(name) */
6934 .flg_export = 1,
6935 .flg_read_only = 1,
6936 };
Eric Andersen25f27032001-04-26 23:22:31 +00006937 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006938 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006939 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006940 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006941
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006942 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02006943 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006944 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006945#if !BB_MMU
6946 G.argv0_for_re_execing = argv[0];
6947#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006948 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006949 G.shell_ver = const_shell_ver; /* copying struct here */
6950 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006951 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006952 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6953 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006954 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006955 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006956 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006957 if (e) while (*e) {
6958 char *value = strchr(*e, '=');
6959 if (value) { /* paranoia */
6960 cur_var->next = xzalloc(sizeof(*cur_var));
6961 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006962 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006963 cur_var->max_len = strlen(*e);
6964 cur_var->flg_export = 1;
6965 }
6966 e++;
6967 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006968 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006969 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02006970 putenv((char *)hush_version_str);
6971
6972 /* Export PWD */
6973 set_pwd_var(/*exp:*/ 1);
6974 /* bash also exports SHLVL and _,
6975 * and sets (but doesn't export) the following variables:
6976 * BASH=/bin/bash
6977 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6978 * BASH_VERSION='3.2.0(1)-release'
6979 * HOSTTYPE=i386
6980 * MACHTYPE=i386-pc-linux-gnu
6981 * OSTYPE=linux-gnu
6982 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02006983 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02006984 * EUID=<NNNNN>
6985 * UID=<NNNNN>
6986 * GROUPS=()
6987 * LINES=<NNN>
6988 * COLUMNS=<NNN>
6989 * BASH_ARGC=()
6990 * BASH_ARGV=()
6991 * BASH_LINENO=()
6992 * BASH_SOURCE=()
6993 * DIRSTACK=()
6994 * PIPESTATUS=([0]="0")
6995 * HISTFILE=/<xxx>/.bash_history
6996 * HISTFILESIZE=500
6997 * HISTSIZE=500
6998 * MAILCHECK=60
6999 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7000 * SHELL=/bin/bash
7001 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7002 * TERM=dumb
7003 * OPTERR=1
7004 * OPTIND=1
7005 * IFS=$' \t\n'
7006 * PS1='\s-\v\$ '
7007 * PS2='> '
7008 * PS4='+ '
7009 */
7010
Denis Vlasenko38f63192007-01-22 09:03:07 +00007011#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007012 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007013#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007014 G.global_argc = argc;
7015 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007016 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007017 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007018
Denis Vlasenkoed782372009-04-10 00:45:02 +00007019 if (setjmp(die_jmp)) {
7020 /* xfunc has failed! die die die */
7021 /* no EXIT traps, this is an escape hatch! */
7022 G.exiting = 1;
7023 hush_exit(xfunc_error_retval);
7024 }
7025
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007026 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007027 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007028 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007029 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007030 * in order to intercept (more) signals.
7031 */
7032
7033 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007034 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007035 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007036 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007037 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007038#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007039 "<:$:R:V:"
7040# if ENABLE_HUSH_FUNCTIONS
7041 "F:"
7042# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007043#endif
7044 );
7045 if (opt <= 0)
7046 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007047 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007048 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007049 /* Possibilities:
7050 * sh ... -c 'script'
7051 * sh ... -c 'script' ARG0 [ARG1...]
7052 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007053 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007054 * "" needs to be replaced with NULL
7055 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007056 * Note: the form without ARG0 never happens:
7057 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007058 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007059 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007060 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007061 G.root_ppid = getppid();
7062 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007063 G.global_argv = argv + optind;
7064 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007065 if (builtin_argc) {
7066 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7067 const struct built_in_command *x;
7068
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007069 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007070 x = find_builtin(optarg);
7071 if (x) { /* paranoia */
7072 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7073 G.global_argv += builtin_argc;
7074 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007075 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007076 }
7077 goto final_return;
7078 }
7079 if (!G.global_argv[0]) {
7080 /* -c 'script' (no params): prevent empty $0 */
7081 G.global_argv--; /* points to argv[i] of 'script' */
7082 G.global_argv[0] = argv[0];
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007083 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007084 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007085 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007086 goto final_return;
7087 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007088 /* Well, we cannot just declare interactiveness,
7089 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007090 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007091 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007092 case 's':
7093 /* "-s" means "read from stdin", but this is how we always
7094 * operate, so simply do nothing here. */
7095 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007096#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007097 case '<': /* "big heredoc" support */
7098 full_write(STDOUT_FILENO, optarg, strlen(optarg));
7099 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007100 case '$': {
7101 unsigned long long empty_trap_mask;
7102
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007103 G.root_pid = bb_strtou(optarg, &optarg, 16);
7104 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007105 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7106 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007107 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7108 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007109 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007110 optarg++;
7111 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007112 optarg++;
7113 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7114 if (empty_trap_mask != 0) {
7115 int sig;
7116 init_sigmasks();
7117 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7118 for (sig = 1; sig < NSIG; sig++) {
7119 if (empty_trap_mask & (1LL << sig)) {
7120 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7121 sigaddset(&G.blocked_set, sig);
7122 }
7123 }
7124 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7125 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007126# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007127 optarg++;
7128 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007129# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007130 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007131 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007132 case 'R':
7133 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007134 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007135 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007136# if ENABLE_HUSH_FUNCTIONS
7137 case 'F': {
7138 struct function *funcp = new_function(optarg);
7139 /* funcp->name is already set to optarg */
7140 /* funcp->body is set to NULL. It's a special case. */
7141 funcp->body_as_string = argv[optind];
7142 optind++;
7143 break;
7144 }
7145# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007146#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007147 case 'n':
7148 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00007149 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007150 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007151 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007152#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007153 fprintf(stderr, "Usage: sh [FILE]...\n"
7154 " or: sh -c command [args]...\n\n");
7155 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007156#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007157 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007158#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007159 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007160 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007161
Denys Vlasenkodea47882009-10-09 15:40:49 +02007162 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007163 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007164 G.root_ppid = getppid();
7165 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007166
7167 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007168 if (argv[0] && argv[0][0] == '-') {
7169 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007170 debug_printf("sourcing /etc/profile\n");
7171 input = fopen_for_read("/etc/profile");
7172 if (input != NULL) {
7173 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007174 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007175 parse_and_run_file(input);
7176 fclose(input);
7177 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007178 /* bash: after sourcing /etc/profile,
7179 * tries to source (in the given order):
7180 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007181 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007182 * bash also sources ~/.bash_logout on exit.
7183 * If called as sh, skips .bash_XXX files.
7184 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007185 }
7186
Denis Vlasenkof9375282009-04-05 19:13:39 +00007187 if (argv[optind]) {
7188 FILE *input;
7189 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007190 * "bash <script>" (which is never interactive (unless -i?))
7191 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007192 * If called as sh, does the same but with $ENV.
7193 */
7194 debug_printf("running script '%s'\n", argv[optind]);
7195 G.global_argv = argv + optind;
7196 G.global_argc = argc - optind;
7197 input = xfopen_for_read(argv[optind]);
7198 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007199 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007200 parse_and_run_file(input);
7201#if ENABLE_FEATURE_CLEAN_UP
7202 fclose(input);
7203#endif
7204 goto final_return;
7205 }
7206
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007207 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007208 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007209 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007210
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007211 /* A shell is interactive if the '-i' flag was given,
7212 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007213 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007214 * no arguments remaining or the -s flag given
7215 * standard input is a terminal
7216 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007217 * Refer to Posix.2, the description of the 'sh' utility.
7218 */
7219#if ENABLE_HUSH_JOB
7220 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007221 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7222 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7223 if (G_saved_tty_pgrp < 0)
7224 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007225
7226 /* try to dup stdin to high fd#, >= 255 */
7227 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7228 if (G_interactive_fd < 0) {
7229 /* try to dup to any fd */
7230 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007231 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007232 /* give up */
7233 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007234 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007235 }
7236 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007237// TODO: track & disallow any attempts of user
7238// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007239 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007240 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007241 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007242 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007243
Mike Frysinger38478a62009-05-20 04:48:06 -04007244 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007245 /* If we were run as 'hush &', sleep until we are
7246 * in the foreground (tty pgrp == our pgrp).
7247 * If we get started under a job aware app (like bash),
7248 * make sure we are now in charge so we don't fight over
7249 * who gets the foreground */
7250 while (1) {
7251 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007252 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7253 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007254 break;
7255 /* send TTIN to ourself (should stop us) */
7256 kill(- shell_pgrp, SIGTTIN);
7257 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007258 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007259
Denis Vlasenkof9375282009-04-05 19:13:39 +00007260 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007261 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007262
Mike Frysinger38478a62009-05-20 04:48:06 -04007263 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007264 /* Set other signals to restore saved_tty_pgrp */
7265 set_fatal_handlers();
7266 /* Put ourselves in our own process group
7267 * (bash, too, does this only if ctty is available) */
7268 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7269 /* Grab control of the terminal */
7270 tcsetpgrp(G_interactive_fd, getpid());
7271 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007272 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007273 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007274 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007275 } else {
7276 init_sigmasks();
7277 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007278#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007279 /* No job control compiled in, only prompt/line editing */
7280 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007281 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7282 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007283 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007284 G_interactive_fd = dup(STDIN_FILENO);
7285 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007286 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007287 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007288 }
7289 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007290 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007291 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007292 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007293 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007294#else
7295 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007296 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007297#endif
7298 /* bash:
7299 * if interactive but not a login shell, sources ~/.bashrc
7300 * (--norc turns this off, --rcfile <file> overrides)
7301 */
7302
7303 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007304 /* note: ash and hush share this string */
7305 printf("\n\n%s %s\n"
7306 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7307 "\n",
7308 bb_banner,
7309 "hush - the humble shell"
7310 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007311 }
7312
Denis Vlasenkof9375282009-04-05 19:13:39 +00007313 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007314
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007315 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007316#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007317 if (G.cwd != bb_msg_unknown)
7318 free((char*)G.cwd);
7319 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007320 while (cur_var) {
7321 struct variable *tmp = cur_var;
7322 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007323 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007324 cur_var = cur_var->next;
7325 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007326 }
Eric Andersen25f27032001-04-26 23:22:31 +00007327#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007328 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007329}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007330
7331
7332#if ENABLE_LASH
7333int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7334int lash_main(int argc, char **argv)
7335{
Denys Vlasenko07934912009-08-20 03:40:04 +02007336 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007337 return hush_main(argc, argv);
7338}
7339#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007340
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007341#if ENABLE_MSH
7342int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7343int msh_main(int argc, char **argv)
7344{
7345 //bb_error_msg("msh is deprecated, please use hush instead");
7346 return hush_main(argc, argv);
7347}
7348#endif
7349
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007350
7351/*
7352 * Built-ins
7353 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007354static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007355{
7356 return 0;
7357}
7358
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007359static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007360{
7361 int argc = 0;
7362 while (*argv) {
7363 argc++;
7364 argv++;
7365 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007366 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007367}
7368
7369static int FAST_FUNC builtin_test(char **argv)
7370{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007371 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007372}
7373
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007374static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007375{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007376 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007377}
7378
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007379#if ENABLE_PRINTF
7380static int FAST_FUNC builtin_printf(char **argv)
7381{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007382 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007383}
7384#endif
7385
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007386static char **skip_dash_dash(char **argv)
7387{
7388 argv++;
7389 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7390 argv++;
7391 return argv;
7392}
7393
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007394static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007395{
7396 int rcode = EXIT_SUCCESS;
7397
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007398 argv = skip_dash_dash(argv);
7399 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007400 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007401 /* bash:
7402 * eval "echo Hi; done" ("done" is syntax error):
7403 * "echo Hi" will not execute too.
7404 */
7405 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007406 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007407 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007408 }
7409 return rcode;
7410}
7411
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007412static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007413{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007414 const char *newdir;
7415
7416 argv = skip_dash_dash(argv);
7417 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007418 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007419 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007420 * bash says "bash: cd: HOME not set" and does nothing
7421 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007422 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007423 const char *home = get_local_var_value("HOME");
7424 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007425 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007426 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007427 /* Mimic bash message exactly */
7428 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007429 return EXIT_FAILURE;
7430 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007431 /* Read current dir (get_cwd(1) is inside) and set PWD.
7432 * Note: do not enforce exporting. If PWD was unset or unexported,
7433 * set it again, but do not export. bash does the same.
7434 */
7435 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007436 return EXIT_SUCCESS;
7437}
7438
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007439static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007440{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007441 argv = skip_dash_dash(argv);
7442 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007443 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007444
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007445 /* Careful: we can end up here after [v]fork. Do not restore
7446 * tty pgrp then, only top-level shell process does that */
7447 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7448 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7449
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007450 /* TODO: if exec fails, bash does NOT exit! We do.
7451 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7452 * and tcsetpgrp, and this is inherently racy.
7453 */
7454 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007455}
7456
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007457static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007458{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007459 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007460
7461 /* interactive bash:
7462 * # trap "echo EEE" EXIT
7463 * # exit
7464 * exit
7465 * There are stopped jobs.
7466 * (if there are _stopped_ jobs, running ones don't count)
7467 * # exit
7468 * exit
7469 # EEE (then bash exits)
7470 *
7471 * we can use G.exiting = -1 as indicator "last cmd was exit"
7472 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007473
7474 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007475 argv = skip_dash_dash(argv);
7476 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007477 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007478 /* mimic bash: exit 123abc == exit 255 + error msg */
7479 xfunc_error_retval = 255;
7480 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007481 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007482}
7483
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007484static void print_escaped(const char *s)
7485{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007486 if (*s == '\'')
7487 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007488 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007489 const char *p = strchrnul(s, '\'');
7490 /* print 'xxxx', possibly just '' */
7491 printf("'%.*s'", (int)(p - s), s);
7492 if (*p == '\0')
7493 break;
7494 s = p;
7495 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007496 /* s points to '; print "'''...'''" */
7497 putchar('"');
7498 do putchar('\''); while (*++s == '\'');
7499 putchar('"');
7500 } while (*s);
7501}
7502
Denys Vlasenko295fef82009-06-03 12:47:26 +02007503#if !ENABLE_HUSH_LOCAL
7504#define helper_export_local(argv, exp, lvl) \
7505 helper_export_local(argv, exp)
7506#endif
7507static void helper_export_local(char **argv, int exp, int lvl)
7508{
7509 do {
7510 char *name = *argv;
7511
7512 /* So far we do not check that name is valid (TODO?) */
7513
7514 if (strchr(name, '=') == NULL) {
7515 struct variable *var;
7516
7517 var = get_local_var(name);
7518 if (exp == -1) { /* unexporting? */
7519 /* export -n NAME (without =VALUE) */
7520 if (var) {
7521 var->flg_export = 0;
7522 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7523 unsetenv(name);
7524 } /* else: export -n NOT_EXISTING_VAR: no-op */
7525 continue;
7526 }
7527 if (exp == 1) { /* exporting? */
7528 /* export NAME (without =VALUE) */
7529 if (var) {
7530 var->flg_export = 1;
7531 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7532 putenv(var->varstr);
7533 continue;
7534 }
7535 }
7536 /* Exporting non-existing variable.
7537 * bash does not put it in environment,
7538 * but remembers that it is exported,
7539 * and does put it in env when it is set later.
7540 * We just set it to "" and export. */
7541 /* Or, it's "local NAME" (without =VALUE).
7542 * bash sets the value to "". */
7543 name = xasprintf("%s=", name);
7544 } else {
7545 /* (Un)exporting/making local NAME=VALUE */
7546 name = xstrdup(name);
7547 }
7548 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7549 } while (*++argv);
7550}
7551
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007552static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007553{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007554 unsigned opt_unexport;
7555
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007556#if ENABLE_HUSH_EXPORT_N
7557 /* "!": do not abort on errors */
7558 opt_unexport = getopt32(argv, "!n");
7559 if (opt_unexport == (uint32_t)-1)
7560 return EXIT_FAILURE;
7561 argv += optind;
7562#else
7563 opt_unexport = 0;
7564 argv++;
7565#endif
7566
7567 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007568 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007569 if (e) {
7570 while (*e) {
7571#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007572 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007573#else
7574 /* ash emits: export VAR='VAL'
7575 * bash: declare -x VAR="VAL"
7576 * we follow ash example */
7577 const char *s = *e++;
7578 const char *p = strchr(s, '=');
7579
7580 if (!p) /* wtf? take next variable */
7581 continue;
7582 /* export var= */
7583 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007584 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007585 putchar('\n');
7586#endif
7587 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007588 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007589 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007590 return EXIT_SUCCESS;
7591 }
7592
Denys Vlasenko295fef82009-06-03 12:47:26 +02007593 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007594
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007595 return EXIT_SUCCESS;
7596}
7597
Denys Vlasenko295fef82009-06-03 12:47:26 +02007598#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007599static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007600{
7601 if (G.func_nest_level == 0) {
7602 bb_error_msg("%s: not in a function", argv[0]);
7603 return EXIT_FAILURE; /* bash compat */
7604 }
7605 helper_export_local(argv, 0, G.func_nest_level);
7606 return EXIT_SUCCESS;
7607}
7608#endif
7609
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007610static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007611{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007612 int sig;
7613 char *new_cmd;
7614
7615 if (!G.traps)
7616 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7617
7618 argv++;
7619 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007620 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007621 /* No args: print all trapped */
7622 for (i = 0; i < NSIG; ++i) {
7623 if (G.traps[i]) {
7624 printf("trap -- ");
7625 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007626 /* note: bash adds "SIG", but only if invoked
7627 * as "bash". If called as "sh", or if set -o posix,
7628 * then it prints short signal names.
7629 * We are printing short names: */
7630 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007631 }
7632 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007633 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007634 return EXIT_SUCCESS;
7635 }
7636
7637 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007638 /* If first arg is a number: reset all specified signals */
7639 sig = bb_strtou(*argv, NULL, 10);
7640 if (errno == 0) {
7641 int ret;
7642 process_sig_list:
7643 ret = EXIT_SUCCESS;
7644 while (*argv) {
7645 sig = get_signum(*argv++);
7646 if (sig < 0 || sig >= NSIG) {
7647 ret = EXIT_FAILURE;
7648 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007649 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007650 continue;
7651 }
7652
7653 free(G.traps[sig]);
7654 G.traps[sig] = xstrdup(new_cmd);
7655
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007656 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007657 get_signame(sig), sig, G.traps[sig]);
7658
7659 /* There is no signal for 0 (EXIT) */
7660 if (sig == 0)
7661 continue;
7662
7663 if (new_cmd) {
7664 sigaddset(&G.blocked_set, sig);
7665 } else {
7666 /* There was a trap handler, we are removing it
7667 * (if sig has non-DFL handling,
7668 * we don't need to do anything) */
7669 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7670 continue;
7671 sigdelset(&G.blocked_set, sig);
7672 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007673 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007674 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007675 return ret;
7676 }
7677
7678 if (!argv[1]) { /* no second arg */
7679 bb_error_msg("trap: invalid arguments");
7680 return EXIT_FAILURE;
7681 }
7682
7683 /* First arg is "-": reset all specified to default */
7684 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7685 /* Everything else: set arg as signal handler
7686 * (includes "" case, which ignores signal) */
7687 if (argv[0][0] == '-') {
7688 if (argv[0][1] == '\0') { /* "-" */
7689 /* new_cmd remains NULL: "reset these sigs" */
7690 goto reset_traps;
7691 }
7692 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7693 argv++;
7694 }
7695 /* else: "-something", no special meaning */
7696 }
7697 new_cmd = *argv;
7698 reset_traps:
7699 argv++;
7700 goto process_sig_list;
7701}
7702
Mike Frysinger93cadc22009-05-27 17:06:25 -04007703/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007704static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007705{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007706 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007707
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007708 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007709 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007710 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007711
7712 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007713 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007714 type = "an alias";*/
7715#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007716 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007717 type = "a function";
7718#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007719 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007720 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007721 else if ((path = find_in_path(*argv)) != NULL)
7722 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007723 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007724 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007725 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007726 continue;
7727 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007728
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007729 printf("%s is %s\n", *argv, type);
7730 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007731 }
7732
7733 return ret;
7734}
7735
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007736#if ENABLE_HUSH_JOB
7737/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007738static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007739{
7740 int i, jobnum;
7741 struct pipe *pi;
7742
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007743 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007744 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007745
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007746 /* If they gave us no args, assume they want the last backgrounded task */
7747 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007748 for (pi = G.job_list; pi; pi = pi->next) {
7749 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007750 goto found;
7751 }
7752 }
7753 bb_error_msg("%s: no current job", argv[0]);
7754 return EXIT_FAILURE;
7755 }
7756 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7757 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7758 return EXIT_FAILURE;
7759 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007760 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007761 if (pi->jobid == jobnum) {
7762 goto found;
7763 }
7764 }
7765 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7766 return EXIT_FAILURE;
7767 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007768 /* TODO: bash prints a string representation
7769 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007770 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007771 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007772 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007773 }
7774
7775 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007776 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7777 for (i = 0; i < pi->num_cmds; i++) {
7778 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7779 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007780 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007781 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007782
7783 i = kill(- pi->pgrp, SIGCONT);
7784 if (i < 0) {
7785 if (errno == ESRCH) {
7786 delete_finished_bg_job(pi);
7787 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007788 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007789 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007790 }
7791
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007792 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007793 remove_bg_job(pi);
7794 return checkjobs_and_fg_shell(pi);
7795 }
7796 return EXIT_SUCCESS;
7797}
7798#endif
7799
7800#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007801static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007802{
7803 const struct built_in_command *x;
7804
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007805 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007806 "Built-in commands:\n"
7807 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007808 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01007809 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007810 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007811 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007812 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007813 return EXIT_SUCCESS;
7814}
7815#endif
7816
7817#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007818static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007819{
7820 struct pipe *job;
7821 const char *status_string;
7822
Denis Vlasenko87a86552008-07-29 19:43:10 +00007823 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007824 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007825 status_string = "Stopped";
7826 else
7827 status_string = "Running";
7828
7829 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7830 }
7831 return EXIT_SUCCESS;
7832}
7833#endif
7834
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007835#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007836static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007837{
7838 void *p;
7839 unsigned long l;
7840
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007841# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02007842 /* Optional. Reduces probability of false positives */
7843 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007844# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007845 /* Crude attempt to find where "free memory" starts,
7846 * sans fragmentation. */
7847 p = malloc(240);
7848 l = (unsigned long)p;
7849 free(p);
7850 p = malloc(3400);
7851 if (l < (unsigned long)p) l = (unsigned long)p;
7852 free(p);
7853
7854 if (!G.memleak_value)
7855 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007856
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007857 l -= G.memleak_value;
7858 if ((long)l < 0)
7859 l = 0;
7860 l /= 1024;
7861 if (l > 127)
7862 l = 127;
7863
7864 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7865 return l;
7866}
7867#endif
7868
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007869static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007870{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007871 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007872 return EXIT_SUCCESS;
7873}
7874
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007875static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007876{
Denys Vlasenko03dad222010-01-12 23:29:57 +01007877 const char *r;
7878 char *opt_n = NULL;
7879 char *opt_p = NULL;
7880 char *opt_t = NULL;
7881 char *opt_u = NULL;
7882 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007883
Denys Vlasenko03dad222010-01-12 23:29:57 +01007884 /* "!": do not abort on errors.
7885 * Option string must start with "sr" to match BUILTIN_READ_xxx
7886 */
7887 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
7888 if (read_flags == (uint32_t)-1)
7889 return EXIT_FAILURE;
7890 argv += optind;
7891
7892 r = shell_builtin_read(set_local_var_from_halves,
7893 argv,
7894 get_local_var_value("IFS"), /* can be NULL */
7895 read_flags,
7896 opt_n,
7897 opt_p,
7898 opt_t,
7899 opt_u
7900 );
7901
7902 if ((uintptr_t)r > 1) {
7903 bb_error_msg("%s", r);
7904 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007905 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007906
Denys Vlasenko03dad222010-01-12 23:29:57 +01007907 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007908}
7909
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007910/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7911 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007912 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007913 * set [-abCefhmnuvx] [-o option] [argument...]
7914 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007915 * set -- [argument...]
7916 * set -o
7917 * set +o
7918 * Implementations shall support the options in both their hyphen and
7919 * plus-sign forms. These options can also be specified as options to sh.
7920 * Examples:
7921 * Write out all variables and their values: set
7922 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7923 * Turn on the -x and -v options: set -xv
7924 * Unset all positional parameters: set --
7925 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7926 * Set the positional parameters to the expansion of x, even if x expands
7927 * with a leading '-' or '+': set -- $x
7928 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007929 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007930 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007931static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007932{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007933 int n;
7934 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007935 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007936
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007937 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007938 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007939 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007940 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007941 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007942 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007943
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007944 do {
7945 if (!strcmp(arg, "--")) {
7946 ++argv;
7947 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007948 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00007949 if (arg[0] != '+' && arg[0] != '-')
7950 break;
7951 for (n = 1; arg[n]; ++n)
7952 if (set_mode(arg[0], arg[n]))
7953 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007954 } while ((arg = *++argv) != NULL);
7955 /* Now argv[0] is 1st argument */
7956
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007957 if (arg == NULL)
7958 return EXIT_SUCCESS;
7959 set_argv:
7960
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007961 /* NB: G.global_argv[0] ($0) is never freed/changed */
7962 g_argv = G.global_argv;
7963 if (G.global_args_malloced) {
7964 pp = g_argv;
7965 while (*++pp)
7966 free(*pp);
7967 g_argv[1] = NULL;
7968 } else {
7969 G.global_args_malloced = 1;
7970 pp = xzalloc(sizeof(pp[0]) * 2);
7971 pp[0] = g_argv[0]; /* retain $0 */
7972 g_argv = pp;
7973 }
7974 /* This realloc's G.global_argv */
7975 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7976
7977 n = 1;
7978 while (*++pp)
7979 n++;
7980 G.global_argc = n;
7981
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007982 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007983
7984 /* Nothing known, so abort */
7985 error:
7986 bb_error_msg("set: %s: invalid option", arg);
7987 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007988}
7989
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007990static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007991{
7992 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007993 argv = skip_dash_dash(argv);
7994 if (argv[0]) {
7995 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007996 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007997 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007998 if (G.global_args_malloced) {
7999 int m = 1;
8000 while (m <= n)
8001 free(G.global_argv[m++]);
8002 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008003 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008004 memmove(&G.global_argv[1], &G.global_argv[n+1],
8005 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008006 return EXIT_SUCCESS;
8007 }
8008 return EXIT_FAILURE;
8009}
8010
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008011static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008012{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008013 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008014 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008015 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008016#if ENABLE_HUSH_FUNCTIONS
8017 smallint sv_flg;
8018#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008019
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008020 argv = skip_dash_dash(argv);
8021 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008022 if (!filename) {
8023 /* bash says: "bash: .: filename argument required" */
8024 return 2; /* bash compat */
8025 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008026 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008027 if (!strchr(filename, '/')) {
8028 arg_path = find_in_path(filename);
8029 if (arg_path)
8030 filename = arg_path;
8031 }
8032 input = fopen_or_warn(filename, "r");
8033 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008034 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008035 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008036 return EXIT_FAILURE;
8037 }
8038 close_on_exec_on(fileno(input));
8039
Mike Frysinger885b6f22009-04-18 21:04:25 +00008040#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008041 sv_flg = G.flag_return_in_progress;
8042 /* "we are inside sourced file, ok to use return" */
8043 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008044#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008045 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008046
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008047 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008048 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008049
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008050 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008051#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008052 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008053#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008054
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008055 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008056}
8057
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008058static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008059{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008060 int rc;
8061 mode_t mask;
8062
8063 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008064 argv = skip_dash_dash(argv);
8065 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008066 mode_t old_mask = mask;
8067
8068 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008069 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008070 mask ^= 0777;
8071 if (rc == 0) {
8072 mask = old_mask;
8073 /* bash messages:
8074 * bash: umask: 'q': invalid symbolic mode operator
8075 * bash: umask: 999: octal number out of range
8076 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008077 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008078 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008079 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008080 rc = 1;
8081 /* Mimic bash */
8082 printf("%04o\n", (unsigned) mask);
8083 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008084 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008085 umask(mask);
8086
8087 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008088}
8089
Mike Frysingerd690f682009-03-30 06:50:54 +00008090/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008091static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008092{
Mike Frysingerd690f682009-03-30 06:50:54 +00008093 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008094 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008095
Denis Vlasenko28e67962009-04-26 23:22:40 +00008096 /* "!": do not abort on errors */
8097 /* "+": stop at 1st non-option */
8098 opts = getopt32(argv, "!+vf");
8099 if (opts == (unsigned)-1)
8100 return EXIT_FAILURE;
8101 if (opts == 3) {
8102 bb_error_msg("unset: -v and -f are exclusive");
8103 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008104 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008105 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008106
8107 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008108 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008109 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008110 if (unset_local_var(*argv)) {
8111 /* unset <nonexistent_var> doesn't fail.
8112 * Error is when one tries to unset RO var.
8113 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008114 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008115 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008116 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008117#if ENABLE_HUSH_FUNCTIONS
8118 else {
8119 unset_func(*argv);
8120 }
8121#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008122 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008123 }
8124 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008125}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008126
Mike Frysinger56bdea12009-03-28 20:01:58 +00008127/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008128static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008129{
8130 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008131 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008132
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008133 argv = skip_dash_dash(argv);
8134 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008135 /* Don't care about wait results */
8136 /* Note 1: must wait until there are no more children */
8137 /* Note 2: must be interruptible */
8138 /* Examples:
8139 * $ sleep 3 & sleep 6 & wait
8140 * [1] 30934 sleep 3
8141 * [2] 30935 sleep 6
8142 * [1] Done sleep 3
8143 * [2] Done sleep 6
8144 * $ sleep 3 & sleep 6 & wait
8145 * [1] 30936 sleep 3
8146 * [2] 30937 sleep 6
8147 * [1] Done sleep 3
8148 * ^C <-- after ~4 sec from keyboard
8149 * $
8150 */
8151 sigaddset(&G.blocked_set, SIGCHLD);
8152 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8153 while (1) {
8154 checkjobs(NULL);
8155 if (errno == ECHILD)
8156 break;
8157 /* Wait for SIGCHLD or any other signal of interest */
8158 /* sigtimedwait with infinite timeout: */
8159 sig = sigwaitinfo(&G.blocked_set, NULL);
8160 if (sig > 0) {
8161 sig = check_and_run_traps(sig);
8162 if (sig && sig != SIGCHLD) { /* see note 2 */
8163 ret = 128 + sig;
8164 break;
8165 }
8166 }
8167 }
8168 sigdelset(&G.blocked_set, SIGCHLD);
8169 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8170 return ret;
8171 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008172
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008173 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008174 while (*argv) {
8175 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008176 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008177 /* mimic bash message */
8178 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008179 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008180 }
8181 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008182 if (WIFSIGNALED(status))
8183 ret = 128 + WTERMSIG(status);
8184 else if (WIFEXITED(status))
8185 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008186 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008187 ret = EXIT_FAILURE;
8188 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008189 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008190 ret = 127;
8191 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008192 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008193 }
8194
8195 return ret;
8196}
8197
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008198#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8199static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8200{
8201 if (argv[1]) {
8202 def = bb_strtou(argv[1], NULL, 10);
8203 if (errno || def < def_min || argv[2]) {
8204 bb_error_msg("%s: bad arguments", argv[0]);
8205 def = UINT_MAX;
8206 }
8207 }
8208 return def;
8209}
8210#endif
8211
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008212#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008213static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008214{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008215 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008216 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008217 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008218 return EXIT_SUCCESS; /* bash compat */
8219 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008220 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008221
8222 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8223 if (depth == UINT_MAX)
8224 G.flag_break_continue = BC_BREAK;
8225 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008226 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008227
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008228 return EXIT_SUCCESS;
8229}
8230
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008231static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008232{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008233 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8234 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008235}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008236#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008237
8238#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008239static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008240{
8241 int rc;
8242
8243 if (G.flag_return_in_progress != -1) {
8244 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8245 return EXIT_FAILURE; /* bash compat */
8246 }
8247
8248 G.flag_return_in_progress = 1;
8249
8250 /* bash:
8251 * out of range: wraps around at 256, does not error out
8252 * non-numeric param:
8253 * f() { false; return qwe; }; f; echo $?
8254 * bash: return: qwe: numeric argument required <== we do this
8255 * 255 <== we also do this
8256 */
8257 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8258 return rc;
8259}
8260#endif