blob: 7640bd6ba72205061af51885b16c57e3a9330c86 [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 >&
Denys Vlasenko2e48d532010-05-22 17:30:39 +020053 * subst operator: ${var/[/]expr/expr}
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020054 * brace expansion: one/{two,three,four}
55 * reserved words: function select
56 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020057 * process substitution: <(list) and >(list)
58 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020059 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020060 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020063 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020064 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020066 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko08218012009-06-03 14:43:56 +020067 * export builtin should be special, its arguments are assignments
68 * and therefore expansion of them should be "one-word" expansion:
69 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
70 * compare with:
71 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
72 * ls: cannot access i=a: No such file or directory
73 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020074 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020075 * Note2: bash 3.2.33(1) does this only if export word itself
76 * is not quoted:
77 * $ export i=`echo 'aaa bbb'`; echo "$i"
78 * aaa bbb
79 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
80 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000081 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000082 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000083 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020084#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denys Vlasenko27726cb2009-09-12 14:48:33 +020085#include <malloc.h> /* for malloc_trim */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000086#include <glob.h>
87/* #include <dmalloc.h> */
88#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000089# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000090#endif
Denys Vlasenko03dad222010-01-12 23:29:57 +010091
92#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000093#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000094#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +020095#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +020096# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +020097#else
98# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +020099#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000100#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200101# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000102#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000103
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000104
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200105/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000106#define LEAK_HUNTING 0
107#define BUILD_AS_NOMMU 0
108/* Enable/disable sanity checks. Ok to enable in production,
109 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
110 * Keeping 1 for now even in released versions.
111 */
112#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200113/* Slightly bigger (+200 bytes), but faster hush.
114 * So far it only enables a trick with counting SIGCHLDs and forks,
115 * which allows us to do fewer waitpid's.
116 * (we can detect a case where neither forks were done nor SIGCHLDs happened
117 * and therefore waitpid will return the same result as last time)
118 */
119#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200120/* TODO: implement simplified code for users which do not need ${var%...} ops
121 * So far ${var%...} ops are always enabled:
122 */
123#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000124
125
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000126#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000127# undef BB_MMU
128# undef USE_FOR_NOMMU
129# undef USE_FOR_MMU
130# define BB_MMU 0
131# define USE_FOR_NOMMU(...) __VA_ARGS__
132# define USE_FOR_MMU(...)
133#endif
134
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200135#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100136#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000137/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000138# undef CONFIG_FEATURE_SH_STANDALONE
139# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000140# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100141# undef IF_NOT_FEATURE_SH_STANDALONE
142# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000143# define IF_FEATURE_SH_STANDALONE(...)
144# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000145#endif
146
Denis Vlasenko05743d72008-02-10 12:10:08 +0000147#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000148# undef ENABLE_FEATURE_EDITING
149# define ENABLE_FEATURE_EDITING 0
150# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
151# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000152#endif
153
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000154/* Do we support ANY keywords? */
155#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000156# define HAS_KEYWORDS 1
157# define IF_HAS_KEYWORDS(...) __VA_ARGS__
158# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000159#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000160# define HAS_KEYWORDS 0
161# define IF_HAS_KEYWORDS(...)
162# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000163#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000164
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000165/* If you comment out one of these below, it will be #defined later
166 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000167#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000168/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000169#define debug_printf_parse(...) do {} while (0)
170#define debug_print_tree(a, b) do {} while (0)
171#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000172#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000173#define debug_printf_jobs(...) do {} while (0)
174#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200175#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000176#define debug_printf_glob(...) do {} while (0)
177#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000178#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000179#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000180
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000181#define ERR_PTR ((void*)(long)1)
182
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200183#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000184
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200185#define _SPECIAL_VARS_STR "_*@$!?#"
186#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
187#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
188
189#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000190
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200191struct variable;
192
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000193static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
194
195/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000196 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000197 */
198#if !BB_MMU
199typedef struct nommu_save_t {
200 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200201 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000202 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000203 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000204} nommu_save_t;
205#endif
206
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000207typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000208 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000209#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000210 RES_IF ,
211 RES_THEN ,
212 RES_ELIF ,
213 RES_ELSE ,
214 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000215#endif
216#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000217 RES_FOR ,
218 RES_WHILE ,
219 RES_UNTIL ,
220 RES_DO ,
221 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000222#endif
223#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000224 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000225#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000226#if ENABLE_HUSH_CASE
227 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200228 /* three pseudo-keywords support contrived "case" syntax: */
229 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
230 RES_MATCH , /* "word)" */
231 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000232 RES_ESAC ,
233#endif
234 RES_XXXX ,
235 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000236} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000237
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000238typedef struct o_string {
239 char *data;
240 int length; /* position where data is appended */
241 int maxlen;
242 /* Protect newly added chars against globbing
243 * (by prepending \ to *, ?, [, \) */
244 smallint o_escape;
245 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000246 /* At least some part of the string was inside '' or "",
247 * possibly empty one: word"", wo''rd etc. */
248 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000249 smallint has_empty_slot;
250 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
251} o_string;
252enum {
253 MAYBE_ASSIGNMENT = 0,
254 DEFINITELY_ASSIGNMENT = 1,
255 NOT_ASSIGNMENT = 2,
256 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
257};
258/* Used for initialization: o_string foo = NULL_O_STRING; */
259#define NULL_O_STRING { NULL }
260
261/* I can almost use ordinary FILE*. Is open_memstream() universally
262 * available? Where is it documented? */
263typedef struct in_str {
264 const char *p;
265 /* eof_flag=1: last char in ->p is really an EOF */
266 char eof_flag; /* meaningless if ->p == NULL */
267 char peek_buf[2];
268#if ENABLE_HUSH_INTERACTIVE
269 smallint promptme;
270 smallint promptmode; /* 0: PS1, 1: PS2 */
271#endif
272 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200273 int (*get) (struct in_str *) FAST_FUNC;
274 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000275} in_str;
276#define i_getch(input) ((input)->get(input))
277#define i_peek(input) ((input)->peek(input))
278
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200279/* The descrip member of this structure is only used to make
280 * debugging output pretty */
281static const struct {
282 int mode;
283 signed char default_fd;
284 char descrip[3];
285} redir_table[] = {
286 { O_RDONLY, 0, "<" },
287 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
288 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
289 { O_CREAT|O_RDWR, 1, "<>" },
290 { O_RDONLY, 0, "<<" },
291/* Should not be needed. Bogus default_fd helps in debugging */
292/* { O_RDONLY, 77, "<<" }, */
293};
294
Eric Andersen25f27032001-04-26 23:22:31 +0000295struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000296 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000297 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000298 int rd_fd; /* fd to redirect */
299 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
300 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000301 smallint rd_type; /* (enum redir_type) */
302 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000303 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200304 * bit 0: do we need to trim leading tabs?
305 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000306 */
Eric Andersen25f27032001-04-26 23:22:31 +0000307};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000308typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200309 REDIRECT_INPUT = 0,
310 REDIRECT_OVERWRITE = 1,
311 REDIRECT_APPEND = 2,
312 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000313 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200314 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000315
316 REDIRFD_CLOSE = -3,
317 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000318 REDIRFD_TO_FILE = -1,
319 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000320
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000321 HEREDOC_SKIPTABS = 1,
322 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000323} redir_type;
324
Eric Andersen25f27032001-04-26 23:22:31 +0000325
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000326struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000327 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000328 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000329 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200330 smallint cmd_type; /* CMD_xxx */
331#define CMD_NORMAL 0
332#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200333
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200334/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200335#if ENABLE_HUSH_BASH_COMPAT
336# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000337#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200338
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200339/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200340//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200341// It is hard to implement correctly, it adds significant amounts of tricky code,
342// and all this is only useful for really obscure export statements
343// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
344// guards the code which implements it, but I have doubts it works
345// in all cases (especially with mixed globbed/non-globbed arguments)
346
347#if ENABLE_HUSH_FUNCTIONS
348# define CMD_FUNCDEF 3
349#endif
350
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200351 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
352 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000353#if !BB_MMU
354 char *group_as_string;
355#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000356#if ENABLE_HUSH_FUNCTIONS
357 struct function *child_func;
358/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200359 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000360 * When we execute "f1() {a;}" cmd, we create new function and clear
361 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200362 * When we execute "f1() {b;}", we notice that f1 exists,
363 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000364 * we put those fields back into cmd->xxx
365 * (struct function has ->parent_cmd ptr to facilitate that).
366 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
367 * Without this trick, loop would execute a;b;b;b;...
368 * instead of correct sequence a;b;a;b;...
369 * When command is freed, it severs the link
370 * (sets ->child_func->parent_cmd to NULL).
371 */
372#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000373 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000374/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
375 * and on execution these are substituted with their values.
376 * Substitution can make _several_ words out of one argv[n]!
377 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000378 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000379 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000380 struct redir_struct *redirects; /* I/O redirections */
381};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000382/* Is there anything in this command at all? */
383#define IS_NULL_CMD(cmd) \
384 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
385
Eric Andersen25f27032001-04-26 23:22:31 +0000386
387struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000388 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000389 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000390 int alive_cmds; /* number of commands running (not exited) */
391 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000392#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000393 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000394 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000395 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000396#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000397 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000398 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000399 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
400 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000401};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000402typedef enum pipe_style {
403 PIPE_SEQ = 1,
404 PIPE_AND = 2,
405 PIPE_OR = 3,
406 PIPE_BG = 4,
407} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000408/* Is there anything in this pipe at all? */
409#define IS_NULL_PIPE(pi) \
410 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000411
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000412/* This holds pointers to the various results of parsing */
413struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000414 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000415 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000416 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000417 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000418 /* last command in pipe (being constructed right now) */
419 struct command *command;
420 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000421 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000422#if !BB_MMU
423 o_string as_string;
424#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000425#if HAS_KEYWORDS
426 smallint ctx_res_w;
427 smallint ctx_inverted; /* "! cmd | cmd" */
428#if ENABLE_HUSH_CASE
429 smallint ctx_dsemicolon; /* ";;" seen */
430#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000431 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
432 int old_flag;
433 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000434 * example: "if pipe1; pipe2; then pipe3; fi"
435 * when we see "if" or "then", we malloc and copy current context,
436 * and make ->stack point to it. then we parse pipeN.
437 * when closing "then" / fi" / whatever is found,
438 * we move list_head into ->stack->command->group,
439 * copy ->stack into current context, and delete ->stack.
440 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000441 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000442 struct parse_context *stack;
443#endif
444};
445
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000446/* On program start, environ points to initial environment.
447 * putenv adds new pointers into it, unsetenv removes them.
448 * Neither of these (de)allocates the strings.
449 * setenv allocates new strings in malloc space and does putenv,
450 * and thus setenv is unusable (leaky) for shell's purposes */
451#define setenv(...) setenv_is_leaky_dont_use()
452struct variable {
453 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000454 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200455#if ENABLE_HUSH_LOCAL
456 unsigned func_nest_level;
457#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000458 int max_len; /* if > 0, name is part of initial env; else name is malloced */
459 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000460 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000461};
462
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000463enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000464 BC_BREAK = 1,
465 BC_CONTINUE = 2,
466};
467
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000468#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000469struct function {
470 struct function *next;
471 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000472 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000473 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200474# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000475 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200476# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000477};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000478#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000479
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000480
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000481/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000482/* Sorted roughly by size (smaller offsets == smaller code) */
483struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000484 /* interactive_fd != 0 means we are an interactive shell.
485 * If we are, then saved_tty_pgrp can also be != 0, meaning
486 * that controlling tty is available. With saved_tty_pgrp == 0,
487 * job control still works, but terminal signals
488 * (^C, ^Z, ^Y, ^\) won't work at all, and background
489 * process groups can only be created with "cmd &".
490 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
491 * to give tty to the foreground process group,
492 * and will take it back when the group is stopped (^Z)
493 * or killed (^C).
494 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000495#if ENABLE_HUSH_INTERACTIVE
496 /* 'interactive_fd' is a fd# open to ctty, if we have one
497 * _AND_ if we decided to act interactively */
498 int interactive_fd;
499 const char *PS1;
500 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000501# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000502#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000503# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000504#endif
505#if ENABLE_FEATURE_EDITING
506 line_input_t *line_input_state;
507#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000508 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200509 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000510 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200511#if ENABLE_HUSH_RANDOM_SUPPORT
512 random_t random_gen;
513#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000514#if ENABLE_HUSH_JOB
515 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000516 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000517 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000518 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400519# define G_saved_tty_pgrp (G.saved_tty_pgrp)
520#else
521# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000522#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000523 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000524#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000525 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000526#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000527#if ENABLE_HUSH_FUNCTIONS
528 /* 0: outside of a function (or sourced file)
529 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000530 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000531 */
532 smallint flag_return_in_progress;
533#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000534 smallint fake_mode;
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200535 smallint x_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000536 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000537 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000538 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000539 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000540 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100541 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000542 /* how many non-NULL argv's we have. NB: $# + 1 */
543 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000544 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000545#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000546 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000547#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000548#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000549 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000550 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000551#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000552 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000553 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000554 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000555 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000556#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000557 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200558# if ENABLE_HUSH_LOCAL
559 struct variable **shadowed_vars_pp;
560 unsigned func_nest_level;
561# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000562#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000563 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200564#if ENABLE_HUSH_FAST
565 unsigned count_SIGCHLD;
566 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200567 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200568#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000569 /* which signals have non-DFL handler (even with no traps set)? */
570 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000571 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000572 sigset_t blocked_set;
573 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000574#if HUSH_DEBUG
575 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000576 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000577#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200578 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000579};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000580#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000581/* Not #defining name to G.name - this quickly gets unwieldy
582 * (too many defines). Also, I actually prefer to see when a variable
583 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000584#define INIT_G() do { \
585 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
586} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000587
588
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000589/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200590static int builtin_cd(char **argv) FAST_FUNC;
591static int builtin_echo(char **argv) FAST_FUNC;
592static int builtin_eval(char **argv) FAST_FUNC;
593static int builtin_exec(char **argv) FAST_FUNC;
594static int builtin_exit(char **argv) FAST_FUNC;
595static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000596#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200597static int builtin_fg_bg(char **argv) FAST_FUNC;
598static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000599#endif
600#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200601static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000602#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200603#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200604static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200605#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000606#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200607static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000608#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400609#if ENABLE_PRINTF
610static int builtin_printf(char **argv) FAST_FUNC;
611#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200612static int builtin_pwd(char **argv) FAST_FUNC;
613static int builtin_read(char **argv) FAST_FUNC;
614static int builtin_set(char **argv) FAST_FUNC;
615static int builtin_shift(char **argv) FAST_FUNC;
616static int builtin_source(char **argv) FAST_FUNC;
617static int builtin_test(char **argv) FAST_FUNC;
618static int builtin_trap(char **argv) FAST_FUNC;
619static int builtin_type(char **argv) FAST_FUNC;
620static int builtin_true(char **argv) FAST_FUNC;
621static int builtin_umask(char **argv) FAST_FUNC;
622static int builtin_unset(char **argv) FAST_FUNC;
623static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000624#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200625static int builtin_break(char **argv) FAST_FUNC;
626static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000627#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000628#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200629static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000630#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000631
632/* Table of built-in functions. They can be forked or not, depending on
633 * context: within pipes, they fork. As simple commands, they do not.
634 * When used in non-forking context, they can change global variables
635 * in the parent shell process. If forked, of course they cannot.
636 * For example, 'unset foo | whatever' will parse and run, but foo will
637 * still be set at the end. */
638struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100639 const char *b_cmd;
640 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000641#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100642 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200643# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000644#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200645# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000646#endif
647};
648
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200649static const struct built_in_command bltins1[] = {
650 BLTIN("." , builtin_source , "Run commands in a file"),
651 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000652#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200653 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000654#endif
655#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200656 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000657#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200658 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000659#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200660 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000661#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200662 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
663 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
664 BLTIN("exit" , builtin_exit , "Exit"),
665 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000666#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200667 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000668#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000669#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200670 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000671#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000672#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200673 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000674#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200675#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200676 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200677#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000678#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200679 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000680#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200681 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000682#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200683 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000684#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200685 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
686 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200687#if ENABLE_HUSH_BASH_COMPAT
688 BLTIN("source" , builtin_source , "Run commands in a file"),
689#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200690 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100691 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100692 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200693 BLTIN("umask" , builtin_umask , "Set file creation mask"),
694 BLTIN("unset" , builtin_unset , "Unset variables"),
695 BLTIN("wait" , builtin_wait , "Wait for process"),
696};
697/* For now, echo and test are unconditionally enabled.
698 * Maybe make it configurable? */
699static const struct built_in_command bltins2[] = {
700 BLTIN("[" , builtin_test , NULL),
701 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400702#if ENABLE_PRINTF
703 BLTIN("printf" , builtin_printf , NULL),
704#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200705 BLTIN("pwd" , builtin_pwd , NULL),
706 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000707};
708
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000709
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000710/* Debug printouts.
711 */
712#if HUSH_DEBUG
713/* prevent disasters with G.debug_indent < 0 */
714# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
715# define debug_enter() (G.debug_indent++)
716# define debug_leave() (G.debug_indent--)
717#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200718# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000719# define debug_enter() ((void)0)
720# define debug_leave() ((void)0)
721#endif
722
723#ifndef debug_printf
724# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
725#endif
726
727#ifndef debug_printf_parse
728# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
729#endif
730
731#ifndef debug_printf_exec
732#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
733#endif
734
735#ifndef debug_printf_env
736# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
737#endif
738
739#ifndef debug_printf_jobs
740# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
741# define DEBUG_JOBS 1
742#else
743# define DEBUG_JOBS 0
744#endif
745
746#ifndef debug_printf_expand
747# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
748# define DEBUG_EXPAND 1
749#else
750# define DEBUG_EXPAND 0
751#endif
752
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200753#ifndef debug_printf_varexp
754# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
755#endif
756
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000757#ifndef debug_printf_glob
758# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
759# define DEBUG_GLOB 1
760#else
761# define DEBUG_GLOB 0
762#endif
763
764#ifndef debug_printf_list
765# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
766#endif
767
768#ifndef debug_printf_subst
769# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
770#endif
771
772#ifndef debug_printf_clean
773# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
774# define DEBUG_CLEAN 1
775#else
776# define DEBUG_CLEAN 0
777#endif
778
779#if DEBUG_EXPAND
780static void debug_print_strings(const char *prefix, char **vv)
781{
782 indent();
783 fprintf(stderr, "%s:\n", prefix);
784 while (*vv)
785 fprintf(stderr, " '%s'\n", *vv++);
786}
787#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200788# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000789#endif
790
791
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000792/* Leak hunting. Use hush_leaktool.sh for post-processing.
793 */
794#if LEAK_HUNTING
795static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000796{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000797 void *ptr = xmalloc((size + 0xff) & ~0xff);
798 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
799 return ptr;
800}
801static void *xxrealloc(int lineno, void *ptr, size_t size)
802{
803 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
804 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
805 return ptr;
806}
807static char *xxstrdup(int lineno, const char *str)
808{
809 char *ptr = xstrdup(str);
810 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
811 return ptr;
812}
813static void xxfree(void *ptr)
814{
815 fdprintf(2, "free %p\n", ptr);
816 free(ptr);
817}
Denys Vlasenko8391c482010-05-22 17:50:43 +0200818# define xmalloc(s) xxmalloc(__LINE__, s)
819# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
820# define xstrdup(s) xxstrdup(__LINE__, s)
821# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000822#endif
823
824
825/* Syntax and runtime errors. They always abort scripts.
826 * In interactive use they usually discard unparsed and/or unexecuted commands
827 * and return to the prompt.
828 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
829 */
830#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200831# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000832# define syntax_error(lineno, msg) syntax_error(msg)
833# define syntax_error_at(lineno, msg) syntax_error_at(msg)
834# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
835# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
836# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000837#endif
838
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000839static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000840{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000841 va_list p;
842
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000843#if HUSH_DEBUG >= 2
844 bb_error_msg("hush.c:%u", lineno);
845#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000846 va_start(p, fmt);
847 bb_verror_msg(fmt, p, NULL);
848 va_end(p);
849 if (!G_interactive_fd)
850 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000851}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000852
853static void syntax_error(unsigned lineno, const char *msg)
854{
855 if (msg)
856 die_if_script(lineno, "syntax error: %s", msg);
857 else
858 die_if_script(lineno, "syntax error", NULL);
859}
860
861static void syntax_error_at(unsigned lineno, const char *msg)
862{
863 die_if_script(lineno, "syntax error at '%s'", msg);
864}
865
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400866static void syntax_error_unterm_str(unsigned lineno, const char *s)
867{
868 die_if_script(lineno, "syntax error: unterminated %s", s);
869}
870
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000871/* It so happens that all such cases are totally fatal
872 * even if shell is interactive: EOF while looking for closing
873 * delimiter. There is nowhere to read stuff from after that,
874 * it's EOF! The only choice is to terminate.
875 */
876static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000877static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000878{
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400879 char msg[2] = { ch, '\0' };
880 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000881 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000882}
883
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200884static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000885{
886 char msg[2];
887 msg[0] = ch;
888 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200889 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000890}
891
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000892#if HUSH_DEBUG < 2
893# undef die_if_script
894# undef syntax_error
895# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000896# undef syntax_error_unterm_ch
897# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000898# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000899#else
Denys Vlasenko606291b2009-09-23 23:15:43 +0200900# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000901# define syntax_error(msg) syntax_error(__LINE__, msg)
902# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
903# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
904# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
905# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000906#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000907
Denis Vlasenko552433b2009-04-04 19:29:21 +0000908
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000909#if ENABLE_HUSH_INTERACTIVE
910static void cmdedit_update_prompt(void);
911#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200912# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000913#endif
914
915
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000916/* Utility functions
917 */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000918/* Replace each \x with x in place, return ptr past NUL. */
919static char *unbackslash(char *src)
920{
Denys Vlasenko71885402009-09-24 01:44:13 +0200921 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +0000922 while (1) {
923 if (*src == '\\')
924 src++;
925 if ((*dst++ = *src++) == '\0')
926 break;
927 }
928 return dst;
929}
930
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000931static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000932{
933 int i;
934 unsigned count1;
935 unsigned count2;
936 char **v;
937
938 v = strings;
939 count1 = 0;
940 if (v) {
941 while (*v) {
942 count1++;
943 v++;
944 }
945 }
946 count2 = 0;
947 v = add;
948 while (*v) {
949 count2++;
950 v++;
951 }
952 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
953 v[count1 + count2] = NULL;
954 i = count2;
955 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000956 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000957 return v;
958}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000959#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000960static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
961{
962 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
963 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
964 return ptr;
965}
966#define add_strings_to_strings(strings, add, need_to_dup) \
967 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
968#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000969
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200970/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000971static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000972{
973 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000974 v[0] = add;
975 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000976 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000977}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000978#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000979static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
980{
981 char **ptr = add_string_to_strings(strings, add);
982 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
983 return ptr;
984}
985#define add_string_to_strings(strings, add) \
986 xx_add_string_to_strings(__LINE__, strings, add)
987#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000988
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200989static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000990{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000991 char **v;
992
993 if (!strings)
994 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000995 v = strings;
996 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200997 free(*v);
998 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000999 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001000 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001001}
1002
Denis Vlasenko76d50412008-06-10 16:19:39 +00001003
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001004/* Helpers for setting new $n and restoring them back
1005 */
1006typedef struct save_arg_t {
1007 char *sv_argv0;
1008 char **sv_g_argv;
1009 int sv_g_argc;
1010 smallint sv_g_malloced;
1011} save_arg_t;
1012
1013static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1014{
1015 int n;
1016
1017 sv->sv_argv0 = argv[0];
1018 sv->sv_g_argv = G.global_argv;
1019 sv->sv_g_argc = G.global_argc;
1020 sv->sv_g_malloced = G.global_args_malloced;
1021
1022 argv[0] = G.global_argv[0]; /* retain $0 */
1023 G.global_argv = argv;
1024 G.global_args_malloced = 0;
1025
1026 n = 1;
1027 while (*++argv)
1028 n++;
1029 G.global_argc = n;
1030}
1031
1032static void restore_G_args(save_arg_t *sv, char **argv)
1033{
1034 char **pp;
1035
1036 if (G.global_args_malloced) {
1037 /* someone ran "set -- arg1 arg2 ...", undo */
1038 pp = G.global_argv;
1039 while (*++pp) /* note: does not free $0 */
1040 free(*pp);
1041 free(G.global_argv);
1042 }
1043 argv[0] = sv->sv_argv0;
1044 G.global_argv = sv->sv_g_argv;
1045 G.global_argc = sv->sv_g_argc;
1046 G.global_args_malloced = sv->sv_g_malloced;
1047}
1048
1049
Denis Vlasenkod5762932009-03-31 11:22:57 +00001050/* Basic theory of signal handling in shell
1051 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001052 * This does not describe what hush does, rather, it is current understanding
1053 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001054 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1055 *
1056 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1057 * is finished or backgrounded. It is the same in interactive and
1058 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001059 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001060 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001061 * backgrounds (i.e. stops) or kills all members of currently running
1062 * pipe.
1063 *
1064 * Wait builtin in interruptible by signals for which user trap is set
1065 * or by SIGINT in interactive shell.
1066 *
1067 * Trap handlers will execute even within trap handlers. (right?)
1068 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001069 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1070 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001071 *
1072 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001073 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001074 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001075 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001076 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001077 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001078 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001079 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001080 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001081 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001082 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001083 *
1084 * SIGQUIT: ignore
1085 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001086 * SIGHUP (interactive):
1087 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001088 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001089 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1090 * that all pipe members are stopped. Try this in bash:
1091 * while :; do :; done - ^Z does not background it
1092 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001093 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001094 * of the command line, show prompt. NB: ^C does not send SIGINT
1095 * to interactive shell while shell is waiting for a pipe,
1096 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001097 * Example 1: this waits 5 sec, but does not execute ls:
1098 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1099 * Example 2: this does not wait and does not execute ls:
1100 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1101 * Example 3: this does not wait 5 sec, but executes ls:
1102 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001103 *
1104 * (What happens to signals which are IGN on shell start?)
1105 * (What happens with signal mask on shell start?)
1106 *
1107 * Implementation in hush
1108 * ======================
1109 * We use in-kernel pending signal mask to determine which signals were sent.
1110 * We block all signals which we don't want to take action immediately,
1111 * i.e. we block all signals which need to have special handling as described
1112 * above, and all signals which have traps set.
1113 * After each pipe execution, we extract any pending signals via sigtimedwait()
1114 * and act on them.
1115 *
1116 * unsigned non_DFL_mask: a mask of such "special" signals
1117 * sigset_t blocked_set: current blocked signal set
1118 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001119 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001120 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001121 * "trap 'cmd' SIGxxx":
1122 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001123 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001124 * unblock signals with special interactive handling
1125 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001126 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001127 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001128 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001129 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001130 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001131 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001132 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001133 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001134 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001135 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001136 * Standard says "When a subshell is entered, traps that are not being ignored
1137 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001138 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001139 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001140enum {
1141 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001142 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001143 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001144 | (1 << SIGHUP)
1145 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001146 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001147#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001148 | (1 << SIGTTIN)
1149 | (1 << SIGTTOU)
1150 | (1 << SIGTSTP)
1151#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001152};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001153
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001154#if ENABLE_HUSH_FAST
1155static void SIGCHLD_handler(int sig UNUSED_PARAM)
1156{
1157 G.count_SIGCHLD++;
1158//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1159}
1160#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001161
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001162#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001163
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001164/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001165# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001166/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001167# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001168
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001169/* Restores tty foreground process group, and exits.
1170 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001171 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001172 * or called directly with -EXITCODE.
1173 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001174static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001175static void sigexit(int sig)
1176{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001177 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001178 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001179
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001180 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001181 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001182 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1183 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001184
1185 /* Not a signal, just exit */
1186 if (sig <= 0)
1187 _exit(- sig);
1188
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001189 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001190}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001191#else
1192
Denys Vlasenko8391c482010-05-22 17:50:43 +02001193# define disable_restore_tty_pgrp_on_exit() ((void)0)
1194# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001195
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001196#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001197
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001198/* Restores tty foreground process group, and exits. */
1199static void hush_exit(int exitcode) NORETURN;
1200static void hush_exit(int exitcode)
1201{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001202 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1203 /* Prevent recursion:
1204 * trap "echo Hi; exit" EXIT; exit
1205 */
1206 char *argv[] = { NULL, G.traps[0], NULL };
1207 G.traps[0] = NULL;
1208 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001209 builtin_eval(argv);
1210 free(argv[1]);
1211 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001212
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001213#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001214 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001215 sigexit(- (exitcode & 0xff));
1216#else
1217 exit(exitcode);
1218#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001219}
1220
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001221static int check_and_run_traps(int sig)
1222{
Dan Fandrichfdd7b562010-06-18 22:37:42 -07001223 static const struct timespec zero_timespec;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001224 smalluint save_rcode;
1225 int last_sig = 0;
1226
1227 if (sig)
1228 goto jump_in;
1229 while (1) {
1230 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1231 if (sig <= 0)
1232 break;
1233 jump_in:
1234 last_sig = sig;
1235 if (G.traps && G.traps[sig]) {
1236 if (G.traps[sig][0]) {
1237 /* We have user-defined handler */
1238 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1239 save_rcode = G.last_exitcode;
1240 builtin_eval(argv);
1241 free(argv[1]);
1242 G.last_exitcode = save_rcode;
1243 } /* else: "" trap, ignoring signal */
1244 continue;
1245 }
1246 /* not a trap: special action */
1247 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001248#if ENABLE_HUSH_FAST
1249 case SIGCHLD:
1250 G.count_SIGCHLD++;
1251//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1252 break;
1253#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001254 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001255 /* Builtin was ^C'ed, make it look prettier: */
1256 bb_putchar('\n');
1257 G.flag_SIGINT = 1;
1258 break;
1259#if ENABLE_HUSH_JOB
1260 case SIGHUP: {
1261 struct pipe *job;
1262 /* bash is observed to signal whole process groups,
1263 * not individual processes */
1264 for (job = G.job_list; job; job = job->next) {
1265 if (job->pgrp <= 0)
1266 continue;
1267 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1268 if (kill(- job->pgrp, SIGHUP) == 0)
1269 kill(- job->pgrp, SIGCONT);
1270 }
1271 sigexit(SIGHUP);
1272 }
1273#endif
1274 default: /* ignored: */
1275 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1276 break;
1277 }
1278 }
1279 return last_sig;
1280}
1281
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001282
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001283static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001284{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001285 if (force || G.cwd == NULL) {
1286 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1287 * we must not try to free(bb_msg_unknown) */
1288 if (G.cwd == bb_msg_unknown)
1289 G.cwd = NULL;
1290 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1291 if (!G.cwd)
1292 G.cwd = bb_msg_unknown;
1293 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001294 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001295}
1296
Denis Vlasenko83506862007-11-23 13:11:42 +00001297
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001298/*
1299 * Shell and environment variable support
1300 */
1301static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001302{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001303 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001304 struct variable *cur;
1305 int len;
1306
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001307 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001308 pp = &G.top_var;
1309 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001310 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001311 return pp;
1312 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001313 }
1314 return NULL;
1315}
1316
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001317static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001318{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001319 struct variable **pp = get_ptr_to_local_var(name);
1320 if (pp)
1321 return *pp;
1322 return NULL;
1323}
1324
Denys Vlasenko03dad222010-01-12 23:29:57 +01001325static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001326{
1327 struct variable **pp = get_ptr_to_local_var(name);
1328 if (pp)
1329 return strchr((*pp)->varstr, '=') + 1;
Denys Vlasenkodea47882009-10-09 15:40:49 +02001330 if (strcmp(name, "PPID") == 0)
1331 return utoa(G.root_ppid);
1332 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001333#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001334 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001335 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001336 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001337#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001338 return NULL;
1339}
1340
1341/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001342 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001343 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001344 * 0: do not change export flag
1345 * (if creating new variable, flag will be 0)
1346 * 1: set export flag and putenv the variable
1347 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001348 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001349 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001350#if !BB_MMU && ENABLE_HUSH_LOCAL
1351/* all params are used */
1352#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, local_lvl)
1355#elif BB_MMU && !ENABLE_HUSH_LOCAL
1356#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001357 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001358#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1359#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1360 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001361#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001362static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001363{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001364 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001365 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001366 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001367 int name_len;
1368
Denis Vlasenko950bd722009-04-21 11:23:56 +00001369 eq_sign = strchr(str, '=');
1370 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001371 free(str);
1372 return -1;
1373 }
1374
Denis Vlasenko950bd722009-04-21 11:23:56 +00001375 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001376 var_pp = &G.top_var;
1377 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001378 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001379 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001380 continue;
1381 }
1382 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001383 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001384#if !BB_MMU
1385 if (!flg_read_only)
1386#endif
1387 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001388 free(str);
1389 return -1;
1390 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001391 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001392 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1393 *eq_sign = '\0';
1394 unsetenv(str);
1395 *eq_sign = '=';
1396 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001397#if ENABLE_HUSH_LOCAL
1398 if (cur->func_nest_level < local_lvl) {
1399 /* New variable is declared as local,
1400 * and existing one is global, or local
1401 * from enclosing function.
1402 * Remove and save old one: */
1403 *var_pp = cur->next;
1404 cur->next = *G.shadowed_vars_pp;
1405 *G.shadowed_vars_pp = cur;
1406 /* bash 3.2.33(1) and exported vars:
1407 * # export z=z
1408 * # f() { local z=a; env | grep ^z; }
1409 * # f
1410 * z=a
1411 * # env | grep ^z
1412 * z=z
1413 */
1414 if (cur->flg_export)
1415 flg_export = 1;
1416 break;
1417 }
1418#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001419 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001420 free_and_exp:
1421 free(str);
1422 goto exp;
1423 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001424 if (cur->max_len != 0) {
1425 if (cur->max_len >= strlen(str)) {
1426 /* This one is from startup env, reuse space */
1427 strcpy(cur->varstr, str);
1428 goto free_and_exp;
1429 }
1430 } else {
1431 /* max_len == 0 signifies "malloced" var, which we can
1432 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001433 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001434 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001435 cur->max_len = 0;
1436 goto set_str_and_exp;
1437 }
1438
Denys Vlasenko295fef82009-06-03 12:47:26 +02001439 /* Not found - create new variable struct */
1440 cur = xzalloc(sizeof(*cur));
1441#if ENABLE_HUSH_LOCAL
1442 cur->func_nest_level = local_lvl;
1443#endif
1444 cur->next = *var_pp;
1445 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001446
1447 set_str_and_exp:
1448 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001449#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001450 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001451#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001452 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001453 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001454 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001455 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1456 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001457 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001458 if (flg_export == -1) {
1459 cur->flg_export = 0;
1460 /* unsetenv was already done */
1461 } else {
1462 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1463 return putenv(cur->varstr);
1464 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001465 }
1466 return 0;
1467}
1468
Denys Vlasenko6db47842009-09-05 20:15:17 +02001469/* Used at startup and after each cd */
1470static void set_pwd_var(int exp)
1471{
1472 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1473 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1474}
1475
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001476static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001477{
1478 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001479 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001480
1481 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001482 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001483 var_pp = &G.top_var;
1484 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001485 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1486 if (cur->flg_read_only) {
1487 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001488 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001489 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001490 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001491 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1492 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001493 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1494 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001495 if (!cur->max_len)
1496 free(cur->varstr);
1497 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001498 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001499 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001500 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001501 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001502 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001503}
1504
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001505static int unset_local_var(const char *name)
1506{
1507 return unset_local_var_len(name, strlen(name));
1508}
1509
1510static void unset_vars(char **strings)
1511{
1512 char **v;
1513
1514 if (!strings)
1515 return;
1516 v = strings;
1517 while (*v) {
1518 const char *eq = strchrnul(*v, '=');
1519 unset_local_var_len(*v, (int)(eq - *v));
1520 v++;
1521 }
1522 free(strings);
1523}
1524
Mike Frysinger98c52642009-04-02 10:02:37 +00001525#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko8391c482010-05-22 17:50:43 +02001526# define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1527# define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denys Vlasenko03dad222010-01-12 23:29:57 +01001528static char* FAST_FUNC endofname(const char *name)
Mike Frysinger98c52642009-04-02 10:02:37 +00001529{
1530 char *p;
1531
1532 p = (char *) name;
1533 if (!is_name(*p))
1534 return p;
1535 while (*++p) {
1536 if (!is_in_name(*p))
1537 break;
1538 }
1539 return p;
1540}
Denys Vlasenko6b01b712010-01-24 22:52:21 +01001541#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001542
Denys Vlasenko03dad222010-01-12 23:29:57 +01001543static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001544{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001545 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001546 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001547}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001548
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001549
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001550/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001551 * Helpers for "var1=val1 var2=val2 cmd" feature
1552 */
1553static void add_vars(struct variable *var)
1554{
1555 struct variable *next;
1556
1557 while (var) {
1558 next = var->next;
1559 var->next = G.top_var;
1560 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001561 if (var->flg_export) {
1562 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001563 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001564 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001565 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001566 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001567 var = next;
1568 }
1569}
1570
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001571static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001572{
1573 char **s;
1574 struct variable *old = NULL;
1575
1576 if (!strings)
1577 return old;
1578 s = strings;
1579 while (*s) {
1580 struct variable *var_p;
1581 struct variable **var_pp;
1582 char *eq;
1583
1584 eq = strchr(*s, '=');
1585 if (eq) {
1586 *eq = '\0';
1587 var_pp = get_ptr_to_local_var(*s);
1588 *eq = '=';
1589 if (var_pp) {
1590 /* Remove variable from global linked list */
1591 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001592 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001593 *var_pp = var_p->next;
1594 /* Add it to returned list */
1595 var_p->next = old;
1596 old = var_p;
1597 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001598 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001599 }
1600 s++;
1601 }
1602 return old;
1603}
1604
1605
1606/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001607 * in_str support
1608 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001609static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001610{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001611 int ch = *i->p;
1612 if (ch != '\0') {
1613 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001614 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001615 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001616 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001617}
1618
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001619static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001620{
1621 return *i->p;
1622}
1623
1624#if ENABLE_HUSH_INTERACTIVE
1625
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001626static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001627{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001628 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001629 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001630 if (G.PS1 == NULL)
1631 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001632 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001633 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001634 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001635 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001636 if (G.PS2 == NULL)
1637 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001638}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001639
1640static const char* setup_prompt_string(int promptmode)
1641{
1642 const char *prompt_str;
1643 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001644 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1645 /* Set up the prompt */
1646 if (promptmode == 0) { /* PS1 */
1647 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001648 /* bash uses $PWD value, even if it is set by user.
1649 * It uses current dir only if PWD is unset.
1650 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001651 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001652 prompt_str = G.PS1;
1653 } else
1654 prompt_str = G.PS2;
1655 } else
1656 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001657 debug_printf("result '%s'\n", prompt_str);
1658 return prompt_str;
1659}
1660
1661static void get_user_input(struct in_str *i)
1662{
1663 int r;
1664 const char *prompt_str;
1665
1666 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001667# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001668 /* Enable command line editing only while a command line
1669 * is actually being read */
1670 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001671 G.flag_SIGINT = 0;
1672 /* buglet: SIGINT will not make new prompt to appear _at once_,
1673 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001674 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 +00001675 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001676 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001677 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001678 i->eof_flag = (r < 0);
1679 if (i->eof_flag) { /* EOF/error detected */
1680 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1681 G.user_input_buf[1] = '\0';
1682 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001683# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001684 do {
1685 G.flag_SIGINT = 0;
1686 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001687 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001688 G.user_input_buf[0] = r = fgetc(i->file);
1689 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001690//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001691 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001692 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001693# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001694 i->p = G.user_input_buf;
1695}
1696
1697#endif /* INTERACTIVE */
1698
1699/* This is the magic location that prints prompts
1700 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001701static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001702{
1703 int ch;
1704
1705 /* If there is data waiting, eat it up */
1706 if (i->p && *i->p) {
1707#if ENABLE_HUSH_INTERACTIVE
1708 take_cached:
1709#endif
1710 ch = *i->p++;
1711 if (i->eof_flag && !*i->p)
1712 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001713 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001714 } else {
1715 /* need to double check i->file because we might be doing something
1716 * more complicated by now, like sourcing or substituting. */
1717#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001718 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001719 do {
1720 get_user_input(i);
1721 } while (!*i->p); /* need non-empty line */
1722 i->promptmode = 1; /* PS2 */
1723 i->promptme = 0;
1724 goto take_cached;
1725 }
1726#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001727 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001728 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001729 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001730#if ENABLE_HUSH_INTERACTIVE
1731 if (ch == '\n')
1732 i->promptme = 1;
1733#endif
1734 return ch;
1735}
1736
Denis Vlasenko913a2012009-04-05 22:17:04 +00001737/* All callers guarantee this routine will never
1738 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001739 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001740static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001741{
1742 int ch;
1743 if (i->p && *i->p) {
1744 if (i->eof_flag && !i->p[1])
1745 return EOF;
1746 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001747 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001748 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001749 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001750 i->eof_flag = (ch == EOF);
1751 i->peek_buf[0] = ch;
1752 i->peek_buf[1] = '\0';
1753 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001754 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001755 return ch;
1756}
1757
1758static void setup_file_in_str(struct in_str *i, FILE *f)
1759{
1760 i->peek = file_peek;
1761 i->get = file_get;
1762#if ENABLE_HUSH_INTERACTIVE
1763 i->promptme = 1;
1764 i->promptmode = 0; /* PS1 */
1765#endif
1766 i->file = f;
1767 i->p = NULL;
1768}
1769
1770static void setup_string_in_str(struct in_str *i, const char *s)
1771{
1772 i->peek = static_peek;
1773 i->get = static_get;
1774#if ENABLE_HUSH_INTERACTIVE
1775 i->promptme = 1;
1776 i->promptmode = 0; /* PS1 */
1777#endif
1778 i->p = s;
1779 i->eof_flag = 0;
1780}
1781
1782
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001783/*
1784 * o_string support
1785 */
1786#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001787
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001788static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001789{
1790 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001791 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001792 if (o->data)
1793 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001794}
1795
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001796static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001797{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001798 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001799 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001800}
1801
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001802static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1803{
1804 free(o->data);
1805}
1806
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001807static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001808{
1809 if (o->length + len > o->maxlen) {
1810 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1811 o->data = xrealloc(o->data, 1 + o->maxlen);
1812 }
1813}
1814
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001815static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001816{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001817 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1818 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001819 o->data[o->length] = ch;
1820 o->length++;
1821 o->data[o->length] = '\0';
1822}
1823
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001824static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001825{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001826 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001827 memcpy(&o->data[o->length], str, len);
1828 o->length += len;
1829 o->data[o->length] = '\0';
1830}
1831
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001832static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001833{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001834 o_addblock(o, str, strlen(str));
1835}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02001836
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001837#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001838static void nommu_addchr(o_string *o, int ch)
1839{
1840 if (o)
1841 o_addchr(o, ch);
1842}
1843#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001844# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001845#endif
1846
1847static void o_addstr_with_NUL(o_string *o, const char *str)
1848{
1849 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001850}
1851
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001852static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001853{
1854 while (len) {
1855 o_addchr(o, *str);
1856 if (*str++ == '\\'
1857 && (*str != '*' && *str != '?' && *str != '[')
1858 ) {
1859 o_addchr(o, '\\');
1860 }
1861 len--;
1862 }
1863}
1864
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001865#undef HUSH_BRACE_EXP
1866/*
1867 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
1868 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
1869 * Apparently, on unquoted $v bash still does globbing
1870 * ("v='*.txt'; echo $v" prints all .txt files),
1871 * but NOT brace expansion! Thus, there should be TWO independent
1872 * quoting mechanisms on $v expansion side: one protects
1873 * $v from brace expansion, and other additionally protects "$v" against globbing.
1874 * We have only second one.
1875 */
1876
1877#ifdef HUSH_BRACE_EXP
1878# define MAYBE_BRACES "{}"
1879#else
1880# define MAYBE_BRACES ""
1881#endif
1882
Eric Andersen25f27032001-04-26 23:22:31 +00001883/* My analysis of quoting semantics tells me that state information
1884 * is associated with a destination, not a source.
1885 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001886static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001887{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001888 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001889 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001890 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001891 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001892 o_grow_by(o, sz);
1893 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001894 o->data[o->length] = '\\';
1895 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001896 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001897 o->data[o->length] = ch;
1898 o->length++;
1899 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001900}
1901
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001902static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001903{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001904 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001905 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001906 sz++;
1907 o->data[o->length] = '\\';
1908 o->length++;
1909 }
1910 o_grow_by(o, sz);
1911 o->data[o->length] = ch;
1912 o->length++;
1913 o->data[o->length] = '\0';
1914}
1915
1916static void o_addQstr(o_string *o, const char *str, int len)
1917{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001918 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001919 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001920 return;
1921 }
1922 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001923 char ch;
1924 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001925 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001926 if (ordinary_cnt > len) /* paranoia */
1927 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001928 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001929 if (ordinary_cnt == len)
1930 return;
1931 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001932 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001933
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001934 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001935 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001936 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001937 sz++;
1938 o->data[o->length] = '\\';
1939 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001940 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001941 o_grow_by(o, sz);
1942 o->data[o->length] = ch;
1943 o->length++;
1944 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001945 }
1946}
1947
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001948/* A special kind of o_string for $VAR and `cmd` expansion.
1949 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001950 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001951 * list[i] contains an INDEX (int!) into this string data.
1952 * It means that if list[] needs to grow, data needs to be moved higher up
1953 * but list[i]'s need not be modified.
1954 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001955 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001956 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1957 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001958#if DEBUG_EXPAND || DEBUG_GLOB
1959static void debug_print_list(const char *prefix, o_string *o, int n)
1960{
1961 char **list = (char**)o->data;
1962 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1963 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001964
1965 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001966 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1967 prefix, list, n, string_start, o->length, o->maxlen);
1968 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001969 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001970 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1971 o->data + (int)list[i] + string_start,
1972 o->data + (int)list[i] + string_start);
1973 i++;
1974 }
1975 if (n) {
1976 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001977 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001978 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001979 }
1980}
1981#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001982# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001983#endif
1984
1985/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1986 * in list[n] so that it points past last stored byte so far.
1987 * It returns n+1. */
1988static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001989{
1990 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001991 int string_start;
1992 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001993
1994 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001995 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1996 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001997 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001998 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001999 /* list[n] points to string_start, make space for 16 more pointers */
2000 o->maxlen += 0x10 * sizeof(list[0]);
2001 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002002 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002003 memmove(list + n + 0x10, list + n, string_len);
2004 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002005 } else {
2006 debug_printf_list("list[%d]=%d string_start=%d\n",
2007 n, string_len, string_start);
2008 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002009 } else {
2010 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002011 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2012 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002013 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2014 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002015 o->has_empty_slot = 0;
2016 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002017 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002018 return n + 1;
2019}
2020
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002021/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002022static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002023{
2024 char **list = (char**)o->data;
2025 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2026
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002027 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002028}
2029
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002030#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002031/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2032 * first, it processes even {a} (no commas), second,
2033 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002034 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002035 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002036
2037/* Helper */
2038static int glob_needed(const char *s)
2039{
2040 while (*s) {
2041 if (*s == '\\') {
2042 if (!s[1])
2043 return 0;
2044 s += 2;
2045 continue;
2046 }
2047 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2048 return 1;
2049 s++;
2050 }
2051 return 0;
2052}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002053/* Return pointer to next closing brace or to comma */
2054static const char *next_brace_sub(const char *cp)
2055{
2056 unsigned depth = 0;
2057 cp++;
2058 while (*cp != '\0') {
2059 if (*cp == '\\') {
2060 if (*++cp == '\0')
2061 break;
2062 cp++;
2063 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002064 }
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002065 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2066 break;
2067 if (*cp++ == '{') /*}*/
2068 depth++;
2069 }
2070
2071 return *cp != '\0' ? cp : NULL;
2072}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002073/* Recursive brace globber. Note: may garble pattern[]. */
2074static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002075{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002076 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002077 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002078 const char *next;
2079 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002080 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002081 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002082
2083 debug_printf_glob("glob_brace('%s')\n", pattern);
2084
2085 begin = pattern;
2086 while (1) {
2087 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002088 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002089 if (*begin == '{') /*}*/ {
2090 /* Find the first sub-pattern and at the same time
2091 * find the rest after the closing brace */
2092 next = next_brace_sub(begin);
2093 if (next == NULL) {
2094 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002095 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002096 }
2097 /*{*/ if (*next == '}') {
2098 /* "{abc}" with no commas - illegal
2099 * brace expr, disregard and skip it */
2100 begin = next + 1;
2101 continue;
2102 }
2103 break;
2104 }
2105 if (*begin == '\\' && begin[1] != '\0')
2106 begin++;
2107 begin++;
2108 }
2109 debug_printf_glob("begin:%s\n", begin);
2110 debug_printf_glob("next:%s\n", next);
2111
2112 /* Now find the end of the whole brace expression */
2113 rest = next;
2114 /*{*/ while (*rest != '}') {
2115 rest = next_brace_sub(rest);
2116 if (rest == NULL) {
2117 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002118 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002119 }
2120 debug_printf_glob("rest:%s\n", rest);
2121 }
2122 rest_len = strlen(++rest) + 1;
2123
2124 /* We are sure the brace expression is well-formed */
2125
2126 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002127 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002128
2129 /* We have a brace expression. BEGIN points to the opening {,
2130 * NEXT points past the terminator of the first element, and REST
2131 * points past the final }. We will accumulate result names from
2132 * recursive runs for each brace alternative in the buffer using
2133 * GLOB_APPEND. */
2134
2135 p = begin + 1;
2136 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002137 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002138 memcpy(
2139 mempcpy(
2140 mempcpy(new_pattern_buf,
2141 /* We know the prefix for all sub-patterns */
2142 pattern, begin - pattern),
2143 p, next - p),
2144 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002145
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002146 /* Note: glob_brace() may garble new_pattern_buf[].
2147 * That's why we re-copy prefix every time (1st memcpy above).
2148 */
2149 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002150 /*{*/ if (*next == '}') {
2151 /* We saw the last entry */
2152 break;
2153 }
2154 p = next + 1;
2155 next = next_brace_sub(next);
2156 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002157 free(new_pattern_buf);
2158 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002159
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002160 simple_glob:
2161 {
2162 int gr;
2163 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002164
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002165 memset(&globdata, 0, sizeof(globdata));
2166 gr = glob(pattern, 0, NULL, &globdata);
2167 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2168 if (gr != 0) {
2169 if (gr == GLOB_NOMATCH) {
2170 globfree(&globdata);
2171 /* NB: garbles parameter */
2172 unbackslash(pattern);
2173 o_addstr_with_NUL(o, pattern);
2174 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2175 return o_save_ptr_helper(o, n);
2176 }
2177 if (gr == GLOB_NOSPACE)
2178 bb_error_msg_and_die(bb_msg_memory_exhausted);
2179 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2180 * but we didn't specify it. Paranoia again. */
2181 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2182 }
2183 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2184 char **argv = globdata.gl_pathv;
2185 while (1) {
2186 o_addstr_with_NUL(o, *argv);
2187 n = o_save_ptr_helper(o, n);
2188 argv++;
2189 if (!*argv)
2190 break;
2191 }
2192 }
2193 globfree(&globdata);
2194 }
2195 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002196}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002197/* Performs globbing on last list[],
2198 * saving each result as a new list[].
2199 */
2200static int o_glob(o_string *o, int n)
2201{
2202 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002203
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002204 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2205 if (!o->data)
2206 return o_save_ptr_helper(o, n);
2207 pattern = o->data + o_get_last_ptr(o, n);
2208 debug_printf_glob("glob pattern '%s'\n", pattern);
2209 if (!glob_needed(pattern)) {
2210 /* unbackslash last string in o in place, fix length */
2211 o->length = unbackslash(pattern) - o->data;
2212 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2213 return o_save_ptr_helper(o, n);
2214 }
2215
2216 copy = xstrdup(pattern);
2217 /* "forget" pattern in o */
2218 o->length = pattern - o->data;
2219 n = glob_brace(copy, o, n);
2220 free(copy);
2221 if (DEBUG_GLOB)
2222 debug_print_list("o_glob returning", o, n);
2223 return n;
2224}
2225
Denys Vlasenko8391c482010-05-22 17:50:43 +02002226#else /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002227
2228/* Helper */
2229static int glob_needed(const char *s)
2230{
2231 while (*s) {
2232 if (*s == '\\') {
2233 if (!s[1])
2234 return 0;
2235 s += 2;
2236 continue;
2237 }
2238 if (*s == '*' || *s == '[' || *s == '?')
2239 return 1;
2240 s++;
2241 }
2242 return 0;
2243}
2244/* Performs globbing on last list[],
2245 * saving each result as a new list[].
2246 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002247static int o_glob(o_string *o, int n)
2248{
2249 glob_t globdata;
2250 int gr;
2251 char *pattern;
2252
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002253 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002254 if (!o->data)
2255 return o_save_ptr_helper(o, n);
2256 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002257 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002258 if (!glob_needed(pattern)) {
2259 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002260 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002261 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002262 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002263 return o_save_ptr_helper(o, n);
2264 }
2265
2266 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002267 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2268 * If we glob "*.\*" and don't find anything, we need
2269 * to fall back to using literal "*.*", but GLOB_NOCHECK
2270 * will return "*.\*"!
2271 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002272 gr = glob(pattern, 0, NULL, &globdata);
2273 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002274 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002275 if (gr == GLOB_NOMATCH) {
2276 globfree(&globdata);
2277 goto literal;
2278 }
2279 if (gr == GLOB_NOSPACE)
2280 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002281 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2282 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002283 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002284 }
2285 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2286 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002287 /* "forget" pattern in o */
2288 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002289 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002290 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002291 n = o_save_ptr_helper(o, n);
2292 argv++;
2293 if (!*argv)
2294 break;
2295 }
2296 }
2297 globfree(&globdata);
2298 if (DEBUG_GLOB)
2299 debug_print_list("o_glob returning", o, n);
2300 return n;
2301}
2302
Denys Vlasenko8391c482010-05-22 17:50:43 +02002303#endif /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002304
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002305/* If o->o_glob == 1, glob the string so far remembered.
2306 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002307static int o_save_ptr(o_string *o, int n)
2308{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002309 if (o->o_glob) { /* if globbing is requested */
2310 /* If o->has_empty_slot, list[n] was already globbed
2311 * (if it was requested back then when it was filled)
2312 * so don't do that again! */
2313 if (!o->has_empty_slot)
2314 return o_glob(o, n); /* o_save_ptr_helper is inside */
2315 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002316 return o_save_ptr_helper(o, n);
2317}
2318
2319/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002320static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002321{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002322 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002323 int string_start;
2324
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002325 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2326 if (DEBUG_EXPAND)
2327 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002328 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002329 list = (char**)o->data;
2330 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2331 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002332 while (n) {
2333 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002334 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002335 }
2336 return list;
2337}
2338
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002339
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002340/* Expansion can recurse */
2341#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002342static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002343#endif
2344static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002345#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002346#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002347 parse_stream_dquoted(dest, input, dquote_end)
2348#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002349static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002350 o_string *dest,
2351 struct in_str *input,
2352 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002353
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002354/* expand_strvec_to_strvec() takes a list of strings, expands
2355 * all variable references within and returns a pointer to
2356 * a list of expanded strings, possibly with larger number
2357 * of strings. (Think VAR="a b"; echo $VAR).
2358 * This new list is allocated as a single malloc block.
2359 * NULL-terminated list of char* pointers is at the beginning of it,
2360 * followed by strings themself.
2361 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002362
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002363/* Store given string, finalizing the word and starting new one whenever
2364 * we encounter IFS char(s). This is used for expanding variable values.
2365 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2366static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002367{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002368 while (1) {
2369 int word_len = strcspn(str, G.ifs);
2370 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002371 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002372 o_addQstr(output, str, word_len);
2373 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002374 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002375 str += word_len;
2376 }
2377 if (!*str) /* EOL - do not finalize word */
2378 break;
2379 o_addchr(output, '\0');
2380 debug_print_list("expand_on_ifs", output, n);
2381 n = o_save_ptr(output, n);
2382 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002383 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002384 debug_print_list("expand_on_ifs[1]", output, n);
2385 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002386}
2387
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002388/* Helper to expand $((...)) and heredoc body. These act as if
2389 * they are in double quotes, with the exception that they are not :).
2390 * Just the rules are similar: "expand only $var and `cmd`"
2391 *
2392 * Returns malloced string.
2393 * As an optimization, we return NULL if expansion is not needed.
2394 */
2395static char *expand_pseudo_dquoted(const char *str)
2396{
2397 char *exp_str;
2398 struct in_str input;
2399 o_string dest = NULL_O_STRING;
2400
2401 if (strchr(str, '$') == NULL
2402#if ENABLE_HUSH_TICK
2403 && strchr(str, '`') == NULL
2404#endif
2405 ) {
2406 return NULL;
2407 }
2408
2409 /* We need to expand. Example:
2410 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2411 */
2412 setup_string_in_str(&input, str);
2413 parse_stream_dquoted(NULL, &dest, &input, EOF);
2414 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2415 exp_str = expand_string_to_string(dest.data);
2416 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2417 o_free_unsafe(&dest);
2418 return exp_str;
2419}
2420
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002421#if ENABLE_SH_MATH_SUPPORT
2422static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2423{
2424 arith_eval_hooks_t hooks;
2425 arith_t res;
2426 char *exp_str;
2427
2428 hooks.lookupvar = get_local_var_value;
2429 hooks.setvar = set_local_var_from_halves;
2430 hooks.endofname = endofname;
2431 exp_str = expand_pseudo_dquoted(arg);
2432 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2433 free(exp_str);
2434 return res;
2435}
2436#endif
2437
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002438/* Expand all variable references in given string, adding words to list[]
2439 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2440 * to be filled). This routine is extremely tricky: has to deal with
2441 * variables/parameters with whitespace, $* and $@, and constructs like
2442 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02002443static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002444{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002445 /* or_mask is either 0 (normal case) or 0x80 -
2446 * expansion of right-hand side of assignment == 1-element expand.
2447 * It will also do no globbing, and thus we must not backslash-quote!
2448 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002449 char ored_ch;
2450 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002451
2452 ored_ch = 0;
2453
Denys Vlasenkof37eb392009-10-18 11:46:35 +02002454 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002455 debug_print_list("expand_vars_to_list", output, n);
2456 n = o_save_ptr(output, n);
2457 debug_print_list("expand_vars_to_list[0]", output, n);
2458
2459 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002460 char first_ch;
2461 int i;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002462 char *to_be_freed = NULL;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002463 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002464#if ENABLE_HUSH_TICK
2465 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002466#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002467#if ENABLE_SH_MATH_SUPPORT
2468 char arith_buf[sizeof(arith_t)*3 + 2];
2469#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002470 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002471 debug_print_list("expand_vars_to_list[1]", output, n);
2472 arg = ++p;
2473 p = strchr(p, SPECIAL_VAR_SYMBOL);
2474
2475 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2476 /* "$@" is special. Even if quoted, it can still
2477 * expand to nothing (not even an empty string) */
2478 if ((first_ch & 0x7f) != '@')
2479 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002480
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002481 switch (first_ch & 0x7f) {
2482 /* Highest bit in first_ch indicates that var is double-quoted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483 case '*':
2484 case '@':
2485 i = 1;
2486 if (!G.global_argv[i])
2487 break;
2488 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2489 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002490 smallint sv = output->o_escape;
2491 /* unquoted var's contents should be globbed, so don't escape */
2492 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002493 while (G.global_argv[i]) {
2494 n = expand_on_ifs(output, n, G.global_argv[i]);
2495 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2496 if (G.global_argv[i++][0] && G.global_argv[i]) {
2497 /* this argv[] is not empty and not last:
2498 * put terminating NUL, start new word */
2499 o_addchr(output, '\0');
2500 debug_print_list("expand_vars_to_list[2]", output, n);
2501 n = o_save_ptr(output, n);
2502 debug_print_list("expand_vars_to_list[3]", output, n);
2503 }
2504 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002505 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002506 } else
2507 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2508 * and in this case should treat it like '$*' - see 'else...' below */
2509 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2510 while (1) {
2511 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2512 if (++i >= G.global_argc)
2513 break;
2514 o_addchr(output, '\0');
2515 debug_print_list("expand_vars_to_list[4]", output, n);
2516 n = o_save_ptr(output, n);
2517 }
2518 } else { /* quoted $*: add as one word */
2519 while (1) {
2520 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2521 if (!G.global_argv[++i])
2522 break;
2523 if (G.ifs[0])
2524 o_addchr(output, G.ifs[0]);
2525 }
2526 }
2527 break;
2528 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2529 /* "Empty variable", used to make "" etc to not disappear */
2530 arg++;
2531 ored_ch = 0x80;
2532 break;
2533#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002534 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002535 *p = '\0';
2536 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002537 /* Can't just stuff it into output o_string,
2538 * expanded result may need to be globbed
2539 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002540 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko647553a2009-11-15 19:58:19 +01002541 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenkocddbb612010-05-20 14:27:09 +02002542 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002543 val = subst_result.data;
2544 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002545#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002546#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002547 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002548 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002549 int errcode;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002550
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002551 arg++; /* skip '+' */
2552 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002553 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002554 res = expand_and_evaluate_arith(arg, &errcode);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002555
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002556 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002557 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002558 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002559 case -3:
2560 msg = "exponent less than 0";
2561 break;
2562 case -2:
2563 msg = "divide by 0";
2564 break;
2565 case -5:
2566 msg = "expression recursion loop detected";
2567 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002568 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002569 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002570 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002571 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002572 sprintf(arith_buf, arith_t_fmt, res);
2573 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002574 break;
2575 }
2576#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002577 default: { /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2578 char *var;
2579 char first_char;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002580 char exp_op;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002581 char exp_save = exp_save; /* for compiler */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002582 char *exp_saveptr; /* points to expansion operator */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002583 char *exp_word = exp_word; /* for compiler */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002584
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002585 var = arg;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002586 *p = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002587 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2588 first_char = arg[0] = first_ch & 0x7f;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002589 exp_op = 0;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002590
2591 if (first_char == '#' && arg[1] && !exp_saveptr) {
Mike Frysinger6379bb42009-03-28 18:55:03 +00002592 /* handle length expansion ${#var} */
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002593 var++;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002594 exp_op = 'L';
Mike Frysinger6379bb42009-03-28 18:55:03 +00002595 } else {
2596 /* maybe handle parameter expansion */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002597 if (exp_saveptr /* if 2nd char is one of expansion operators */
2598 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2599 ) {
2600 /* ${?:0}, ${#[:]%0} etc */
2601 exp_saveptr = var + 1;
2602 } else {
2603 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2604 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2605 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002606 exp_op = exp_save = *exp_saveptr;
2607 if (exp_op) {
2608 exp_word = exp_saveptr + 1;
2609 if (exp_op == ':') {
2610 exp_op = *exp_word++;
2611 if (ENABLE_HUSH_BASH_COMPAT
2612 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2613 ) {
2614 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2615 exp_op = ':';
2616 exp_word--;
2617 }
2618 }
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002619 *exp_saveptr = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002620 } /* else: it's not an expansion op, but bare ${var} */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002621 }
2622
2623 /* lookup the variable in question */
2624 if (isdigit(var[0])) {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002625 /* parse_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002626 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002627 if (i < G.global_argc)
2628 val = G.global_argv[i];
2629 /* else val remains NULL: $N with too big N */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002630 } else {
2631 switch (var[0]) {
2632 case '$': /* pid */
2633 val = utoa(G.root_pid);
2634 break;
2635 case '!': /* bg pid */
2636 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2637 break;
2638 case '?': /* exitcode */
2639 val = utoa(G.last_exitcode);
2640 break;
2641 case '#': /* argc */
2642 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2643 break;
2644 default:
2645 val = get_local_var_value(var);
2646 }
2647 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002648
2649 /* handle any expansions */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002650 if (exp_op == 'L') {
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002651 debug_printf_expand("expand: length(%s)=", val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002652 val = utoa(val ? strlen(val) : 0);
2653 debug_printf_expand("%s\n", val);
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002654 } else if (exp_op) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002655 if (exp_op == '%' || exp_op == '#') {
Denys Vlasenko53b51332010-05-20 21:46:45 +02002656 /* Standard-mandated substring removal ops:
2657 * ${parameter%word} - remove smallest suffix pattern
2658 * ${parameter%%word} - remove largest suffix pattern
2659 * ${parameter#word} - remove smallest prefix pattern
2660 * ${parameter##word} - remove largest prefix pattern
2661 *
2662 * Word is expanded to produce a glob pattern.
2663 * Then var's value is matched to it and matching part removed.
2664 */
Mike Frysinger57e74672009-04-09 23:00:33 +00002665 if (val) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002666 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002667 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002668 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002669 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002670 exp_word++;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002671 val = to_be_freed = xstrdup(val);
Denys Vlasenko74369502010-05-21 19:52:01 +02002672 {
2673 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2674 if (exp_exp_word)
2675 exp_word = exp_exp_word;
2676 loc = scan(to_be_freed, exp_word, match_at_left);
2677 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2678 // exp_op, to_be_freed, exp_word, loc);
2679 free(exp_exp_word);
2680 }
2681 if (loc) { /* match was found */
2682 if (match_at_left) /* # or ## */
2683 val = loc;
2684 else /* % or %% */
2685 *loc = '\0';
2686 }
Mike Frysinger57e74672009-04-09 23:00:33 +00002687 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002688 } else if (exp_op == ':') {
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02002689#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002690 /* It's ${var:N[:M]} bashism.
2691 * Note that in encoded form it has TWO parts:
2692 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002693 */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002694 arith_t beg, len;
2695 int errcode = 0;
2696
2697 beg = expand_and_evaluate_arith(exp_word, &errcode);
2698 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2699 *p++ = SPECIAL_VAR_SYMBOL;
2700 exp_word = p;
2701 p = strchr(p, SPECIAL_VAR_SYMBOL);
2702 *p = '\0';
2703 len = expand_and_evaluate_arith(exp_word, &errcode);
2704 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2705
2706 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2707 if (beg < 0) /* bash compat */
2708 beg = 0;
2709 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002710 if (len == 0 || !val || beg >= strlen(val))
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002711 val = "";
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002712 else {
2713 /* Paranoia. What if user entered 9999999999999
2714 * which fits in arith_t but not int? */
2715 if (len >= INT_MAX)
2716 len = INT_MAX;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002717 val = to_be_freed = xstrndup(val + beg, len);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002718 }
2719 debug_printf_varexp("val:'%s'\n", val);
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002720 } else
2721#endif
2722 {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002723 die_if_script("malformed ${%s:...}", var);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002724 val = "";
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002725 }
2726 } else { /* one of "-=+?" */
Denys Vlasenko53b51332010-05-20 21:46:45 +02002727 /* Standard-mandated substitution ops:
2728 * ${var?word} - indicate error if unset
2729 * If var is unset, word (or a message indicating it is unset
2730 * if word is null) is written to standard error
2731 * and the shell exits with a non-zero exit status.
2732 * Otherwise, the value of var is substituted.
2733 * ${var-word} - use default value
2734 * If var is unset, word is substituted.
2735 * ${var=word} - assign and use default value
2736 * If var is unset, word is assigned to var.
2737 * In all cases, final value of var is substituted.
2738 * ${var+word} - use alternative value
2739 * If var is unset, null is substituted.
2740 * Otherwise, word is substituted.
2741 *
2742 * Word is subjected to tilde expansion, parameter expansion,
2743 * command substitution, and arithmetic expansion.
2744 * If word is not needed, it is not expanded.
2745 *
2746 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2747 * but also treat null var as if it is unset.
2748 */
2749 int use_word = (!val || ((exp_save == ':') && !val[0]));
Mike Frysingera4f331d2009-04-07 06:03:22 +00002750 if (exp_op == '+')
Denys Vlasenko53b51332010-05-20 21:46:45 +02002751 use_word = !use_word;
Mike Frysingera4f331d2009-04-07 06:03:22 +00002752 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
Denys Vlasenko53b51332010-05-20 21:46:45 +02002753 (exp_save == ':') ? "true" : "false", use_word);
2754 if (use_word) {
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002755 to_be_freed = expand_pseudo_dquoted(exp_word);
2756 if (to_be_freed)
2757 exp_word = to_be_freed;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002758 if (exp_op == '?') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002759 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002760 die_if_script("%s: %s",
2761 var,
2762 exp_word[0] ? exp_word : "parameter null or not set"
2763 );
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002764//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002765 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002766 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002767 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002768
Mike Frysingera4f331d2009-04-07 06:03:22 +00002769 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002770 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002771 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002772 /* mimic bash message */
2773 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002774 val = NULL;
2775 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002776 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002777 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002778 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002779 }
2780 }
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002781 } /* one of "-=+?" */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002782
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002783 *exp_saveptr = exp_save;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002784 } /* if (exp_op) */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002785
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002786 arg[0] = first_ch;
2787#if ENABLE_HUSH_TICK
2788 store_val:
2789#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002790 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002791 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002792 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002793 /* unquoted var's contents should be globbed, so don't escape */
2794 smallint sv = output->o_escape;
2795 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002796 n = expand_on_ifs(output, n, val);
2797 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002798 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002799 }
2800 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002801 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002802 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002803 } /* default: */
2804 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002805
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002806 if (val) {
2807 o_addQstr(output, val, strlen(val));
2808 }
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002809 free(to_be_freed);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002810 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002811 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002812 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002813
2814#if ENABLE_HUSH_TICK
2815 o_free(&subst_result);
2816#endif
2817 arg = ++p;
2818 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2819
2820 if (arg[0]) {
2821 debug_print_list("expand_vars_to_list[a]", output, n);
2822 /* this part is literal, and it was already pre-quoted
2823 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002824 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002825 debug_print_list("expand_vars_to_list[b]", output, n);
2826 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2827 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2828 ) {
2829 n--;
2830 /* allow to reuse list[n] later without re-growth */
2831 output->has_empty_slot = 1;
2832 } else {
2833 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002834 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002835 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002836}
2837
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002838static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002839{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002840 int n;
2841 char **list;
2842 char **v;
2843 o_string output = NULL_O_STRING;
2844
2845 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002846 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002847 /* (unquoted $var will temporarily switch it off) */
2848 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002849 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002850
2851 n = 0;
2852 v = argv;
2853 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002854 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002855 v++;
2856 }
2857 debug_print_list("expand_variables", &output, n);
2858
2859 /* output.data (malloced in one block) gets returned in "list" */
2860 list = o_finalize_list(&output, n);
2861 debug_print_strings("expand_variables[1]", list);
2862 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002863}
2864
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002865static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002866{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002867 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002868}
2869
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002870#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002871static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2872{
2873 return expand_variables(argv, 0x80);
2874}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002875#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002876
2877#ifdef CMD_SINGLEWORD_NOGLOB_COND
2878static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2879{
2880 int n;
2881 char **list;
2882 char **v;
2883 o_string output = NULL_O_STRING;
2884
2885 n = 0;
2886 v = argv;
2887 while (*v) {
2888 int is_var = is_well_formed_var_name(*v, '=');
2889 /* is_var * 0x80: singleword expansion for vars */
2890 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2891
2892 /* Subtle! expand_vars_to_list did not glob last word yet.
2893 * It does this only when fed with further data.
2894 * Therefore we set globbing flags AFTER it, not before:
2895 */
2896
2897 /* if it is not recognizably abc=...; then: */
2898 output.o_escape = !is_var; /* protect against globbing for "$var" */
2899 /* (unquoted $var will temporarily switch it off) */
2900 output.o_glob = !is_var; /* and indeed do globbing */
2901 v++;
2902 }
2903 debug_print_list("expand_cond", &output, n);
2904
2905 /* output.data (malloced in one block) gets returned in "list" */
2906 list = o_finalize_list(&output, n);
2907 debug_print_strings("expand_cond[1]", list);
2908 return list;
2909}
2910#endif
2911
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002912/* Used for expansion of right hand of assignments */
2913/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2914 * "v=/bin/c*" */
2915static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002916{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002917 char *argv[2], **list;
2918
2919 argv[0] = (char*)str;
2920 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002921 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002922 if (HUSH_DEBUG)
2923 if (!list[0] || list[1])
2924 bb_error_msg_and_die("BUG in varexp2");
2925 /* actually, just move string 2*sizeof(char*) bytes back */
2926 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002927 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002928 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2929 return (char*)list;
2930}
2931
2932/* Used for "eval" builtin */
2933static char* expand_strvec_to_string(char **argv)
2934{
2935 char **list;
2936
2937 list = expand_variables(argv, 0x80);
2938 /* Convert all NULs to spaces */
2939 if (list[0]) {
2940 int n = 1;
2941 while (list[n]) {
2942 if (HUSH_DEBUG)
2943 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2944 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002945 /* bash uses ' ' regardless of $IFS contents */
2946 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002947 n++;
2948 }
2949 }
2950 overlapping_strcpy((char*)list, list[0]);
2951 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2952 return (char*)list;
2953}
2954
2955static char **expand_assignments(char **argv, int count)
2956{
2957 int i;
2958 char **p = NULL;
2959 /* Expand assignments into one string each */
2960 for (i = 0; i < count; i++) {
2961 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2962 }
2963 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002964}
2965
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002966
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002967#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002968/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002969void re_execute_shell(char ***to_free, const char *s,
2970 char *g_argv0, char **g_argv,
2971 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002972
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002973static void reset_traps_to_defaults(void)
2974{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002975 /* This function is always called in a child shell
2976 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002977 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002978 unsigned sig;
2979 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002980
Denys Vlasenko67f71862009-09-25 14:21:06 +02002981 /* Child shells are not interactive.
2982 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2983 * Testcase: (while :; do :; done) + ^Z should background.
2984 * Same goes for SIGTERM, SIGHUP, SIGINT.
2985 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002986 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02002987 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002988
Denys Vlasenko67f71862009-09-25 14:21:06 +02002989 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2990 * Stupid. It can be done with *single* &= op, but we can't use
2991 * the fact that G.blocked_set is implemented as a bitmask
2992 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002993 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2994 sig = 1;
2995 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002996 if (mask & 1) {
2997 /* Careful. Only if no trap or trap is not "" */
2998 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2999 sigdelset(&G.blocked_set, sig);
3000 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003001 mask >>= 1;
3002 if (!mask)
3003 break;
3004 sig++;
3005 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02003006 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003007 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003008
3009 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003010 mask = G.non_DFL_mask;
3011 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02003012 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003013 continue;
3014 free(G.traps[sig]);
3015 G.traps[sig] = NULL;
3016 /* There is no signal for 0 (EXIT) */
3017 if (sig == 0)
3018 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003019 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003020 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02003021 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003022 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003023 continue;
3024 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003025 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003026 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003027}
3028
3029#else /* !BB_MMU */
3030
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003031static void re_execute_shell(char ***to_free, const char *s,
3032 char *g_argv0, char **g_argv,
3033 char **builtin_argv) NORETURN;
3034static void re_execute_shell(char ***to_free, const char *s,
3035 char *g_argv0, char **g_argv,
3036 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003037{
Denys Vlasenko8391c482010-05-22 17:50:43 +02003038# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003039 /* delims + 2 * (number of bytes in printed hex numbers) */
3040 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003041 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003042 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003043# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003044 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003045# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003046 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003047 unsigned cnt;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003048 unsigned long long empty_trap_mask;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003049
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003050 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003051 argv = heredoc_argv;
3052 argv[0] = (char *) G.argv0_for_re_execing;
3053 argv[1] = (char *) "-<";
3054 argv[2] = (char *) s;
3055 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00003056 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003057 goto do_exec;
3058 }
3059
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003060 cnt = 0;
3061 pp = builtin_argv;
3062 if (pp) while (*pp++)
3063 cnt++;
3064
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003065 empty_trap_mask = 0;
3066 if (G.traps) {
3067 int sig;
3068 for (sig = 1; sig < NSIG; sig++) {
3069 if (G.traps[sig] && !G.traps[sig][0])
3070 empty_trap_mask |= 1LL << sig;
3071 }
3072 }
3073
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003074 sprintf(param_buf, NOMMU_HACK_FMT
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003075 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02003076 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003077 , (unsigned) G.last_bg_pid
3078 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003079 , cnt
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003080 , empty_trap_mask
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003081 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003082 );
Denys Vlasenko8391c482010-05-22 17:50:43 +02003083# undef NOMMU_HACK_FMT
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003084 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003085 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003086 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003087 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003088 for (cur = G.top_var; cur; cur = cur->next) {
3089 if (!cur->flg_export || cur->flg_read_only)
3090 cnt += 2;
3091 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003092# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003093 for (funcp = G.top_func; funcp; funcp = funcp->next)
3094 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003095# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003096 pp = g_argv;
3097 while (*pp++)
3098 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003099 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003100 *pp++ = (char *) G.argv0_for_re_execing;
3101 *pp++ = param_buf;
3102 for (cur = G.top_var; cur; cur = cur->next) {
3103 if (cur->varstr == hush_version_str)
3104 continue;
3105 if (cur->flg_read_only) {
3106 *pp++ = (char *) "-R";
3107 *pp++ = cur->varstr;
3108 } else if (!cur->flg_export) {
3109 *pp++ = (char *) "-V";
3110 *pp++ = cur->varstr;
3111 }
3112 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003113# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003114 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3115 *pp++ = (char *) "-F";
3116 *pp++ = funcp->name;
3117 *pp++ = funcp->body_as_string;
3118 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003119# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003120 /* We can pass activated traps here. Say, -Tnn:trap_string
3121 *
3122 * However, POSIX says that subshells reset signals with traps
3123 * to SIG_DFL.
3124 * I tested bash-3.2 and it not only does that with true subshells
3125 * of the form ( list ), but with any forked children shells.
3126 * I set trap "echo W" WINCH; and then tried:
3127 *
3128 * { echo 1; sleep 20; echo 2; } &
3129 * while true; do echo 1; sleep 20; echo 2; break; done &
3130 * true | { echo 1; sleep 20; echo 2; } | cat
3131 *
3132 * In all these cases sending SIGWINCH to the child shell
3133 * did not run the trap. If I add trap "echo V" WINCH;
3134 * _inside_ group (just before echo 1), it works.
3135 *
3136 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003137 * Even if we would use signal handlers instead of signal masking
3138 * in order to implement trap handling,
3139 * exec syscall below resets signals to SIG_DFL for us.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003140 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003141 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003142 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003143 if (builtin_argv) {
3144 while (*++builtin_argv)
3145 *pp++ = *builtin_argv;
3146 *pp++ = (char *) "";
3147 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003148 *pp++ = g_argv0;
3149 while (*g_argv)
3150 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003151 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003152 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003153
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003154 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003155 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3156 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003157 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003158 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003159 if (argv[0][0] == '/')
3160 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003161 xfunc_error_retval = 127;
3162 bb_error_msg_and_die("can't re-execute the shell");
3163}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003164#endif /* !BB_MMU */
3165
3166
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003167static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003168{
3169 struct fd_pair pair;
3170 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003171 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003172 /* the _body_ of heredoc (misleading field name) */
3173 const char *heredoc = redir->rd_filename;
3174 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003175#if !BB_MMU
3176 char **to_free;
3177#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003178
3179 expanded = NULL;
3180 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3181 expanded = expand_pseudo_dquoted(heredoc);
3182 if (expanded)
3183 heredoc = expanded;
3184 }
3185 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003186
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003187 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003188 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003189 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003190
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003191 /* Try writing without forking. Newer kernels have
3192 * dynamically growing pipes. Must use non-blocking write! */
3193 ndelay_on(pair.wr);
3194 while (1) {
3195 written = write(pair.wr, heredoc, len);
3196 if (written <= 0)
3197 break;
3198 len -= written;
3199 if (len == 0) {
3200 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00003201 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003202 return;
3203 }
3204 heredoc += written;
3205 }
3206 ndelay_off(pair.wr);
3207
3208 /* Okay, pipe buffer was not big enough */
3209 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003210 * for the unsuspecting parent process. Child creates a grandchild
3211 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003212 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003213#if !BB_MMU
3214 to_free = NULL;
3215#endif
Pascal Bellard926031b2010-07-04 15:32:38 +02003216 pid = xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003217 if (pid == 0) {
3218 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003219 disable_restore_tty_pgrp_on_exit();
Pascal Bellard926031b2010-07-04 15:32:38 +02003220 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003221 if (pid != 0)
3222 _exit(0);
3223 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003224 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003225#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003226 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003227 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003228#else
3229 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003230 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003231 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003232#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003233 }
3234 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003235#if ENABLE_HUSH_FAST
3236 G.count_SIGCHLD++;
3237//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3238#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003239 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003240#if !BB_MMU
3241 free(to_free);
3242#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003243 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003244 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003245 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003246}
3247
Eric Andersen25f27032001-04-26 23:22:31 +00003248/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3249 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003250static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003251{
3252 int openfd, mode;
3253 struct redir_struct *redir;
3254
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003255 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003256 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003257 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003258 if (squirrel && redir->rd_fd < 3
3259 && squirrel[redir->rd_fd] < 0
3260 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003261 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003262 }
3263 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3264 * of the heredoc */
3265 debug_printf_parse("set heredoc '%s'\n",
3266 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003267 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003268 continue;
3269 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003270
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003271 if (redir->rd_dup == REDIRFD_TO_FILE) {
3272 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003273 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003274 if (redir->rd_filename == NULL) {
3275 /* Something went wrong in the parse.
3276 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003277 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003278 continue;
3279 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003280 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003281 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003282 openfd = open_or_warn(p, mode);
3283 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003284 if (openfd < 0) {
3285 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003286 * bash and ash both lose it as well (though zsh doesn't!) */
3287//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003288 return 1;
3289 }
3290 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003291 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003292 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003293 }
3294
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003295 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003296 if (squirrel && redir->rd_fd < 3
3297 && squirrel[redir->rd_fd] < 0
3298 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003299 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003300 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003301 if (openfd == REDIRFD_CLOSE) {
3302 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003303 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003304 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003305 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003306 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003307 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003308 }
Eric Andersen25f27032001-04-26 23:22:31 +00003309 }
3310 }
3311 return 0;
3312}
3313
3314static void restore_redirects(int squirrel[])
3315{
3316 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003317 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003318 fd = squirrel[i];
3319 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003320 /* We simply die on error */
3321 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003322 }
3323 }
3324}
3325
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003326
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003327static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003328
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003329/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003330static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003331{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003332 char **p;
3333 struct command *command;
3334 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003335 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003336
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003337 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003338 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003339 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003340 for (i = 0; i < pi->num_cmds; i++) {
3341 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003342 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003343 if (command->argv) {
3344 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003345 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003346 }
3347 free_strings(command->argv);
3348 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003349 }
3350 /* not "else if": on syntax error, we may have both! */
3351 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003352 debug_printf_clean(" begin group (cmd_type:%d)\n",
3353 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003354 free_pipe_list(command->group);
3355 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003356 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003357 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003358 /* else is crucial here.
3359 * If group != NULL, child_func is meaningless */
3360#if ENABLE_HUSH_FUNCTIONS
3361 else if (command->child_func) {
3362 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3363 command->child_func->parent_cmd = NULL;
3364 }
3365#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003366#if !BB_MMU
3367 free(command->group_as_string);
3368 command->group_as_string = NULL;
3369#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003370 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003371 debug_printf_clean(" redirect %d%s",
3372 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003373 /* guard against the case >$FOO, where foo is unset or blank */
3374 if (r->rd_filename) {
3375 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3376 free(r->rd_filename);
3377 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003378 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003379 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003380 rnext = r->next;
3381 free(r);
3382 }
3383 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003384 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003385 free(pi->cmds); /* children are an array, they get freed all at once */
3386 pi->cmds = NULL;
3387#if ENABLE_HUSH_JOB
3388 free(pi->cmdtext);
3389 pi->cmdtext = NULL;
3390#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003391}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003392
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003393static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003394{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003395 struct pipe *pi, *next;
3396
3397 for (pi = head; pi; pi = next) {
3398#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003399 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003400#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003401 free_pipe(pi);
3402 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003403 next = pi->next;
3404 /*pi->next = NULL;*/
3405 free(pi);
3406 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003407}
3408
3409
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003410static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003411#if BB_MMU
3412#define parse_stream(pstring, input, end_trigger) \
3413 parse_stream(input, end_trigger)
3414#endif
3415static struct pipe *parse_stream(char **pstring,
3416 struct in_str *input,
3417 int end_trigger);
3418static void parse_and_run_string(const char *s);
3419
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003420
Mike Frysinger93cadc22009-05-27 17:06:25 -04003421static char *find_in_path(const char *arg)
3422{
3423 char *ret = NULL;
3424 const char *PATH = get_local_var_value("PATH");
3425
3426 if (!PATH)
3427 return NULL;
3428
3429 while (1) {
3430 const char *end = strchrnul(PATH, ':');
3431 int sz = end - PATH; /* must be int! */
3432
3433 free(ret);
3434 if (sz != 0) {
3435 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3436 } else {
3437 /* We have xxx::yyyy in $PATH,
3438 * it means "use current dir" */
3439 ret = xstrdup(arg);
3440 }
3441 if (access(ret, F_OK) == 0)
3442 break;
3443
3444 if (*end == '\0') {
3445 free(ret);
3446 return NULL;
3447 }
3448 PATH = end + 1;
3449 }
3450
3451 return ret;
3452}
3453
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003454static const struct built_in_command* find_builtin_helper(const char *name,
3455 const struct built_in_command *x,
3456 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003457{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003458 while (x != end) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01003459 if (strcmp(name, x->b_cmd) != 0) {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003460 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003461 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003462 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003463 debug_printf_exec("found builtin '%s'\n", name);
3464 return x;
3465 }
3466 return NULL;
3467}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003468static const struct built_in_command* find_builtin1(const char *name)
3469{
3470 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3471}
3472static const struct built_in_command* find_builtin(const char *name)
3473{
3474 const struct built_in_command *x = find_builtin1(name);
3475 if (x)
3476 return x;
3477 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3478}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003479
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003480#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003481static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003482{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003483 struct function **funcpp = &G.top_func;
3484 while (*funcpp) {
3485 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003486 break;
3487 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003488 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003489 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003490 return funcpp;
3491}
3492
3493static const struct function *find_function(const char *name)
3494{
3495 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003496 if (funcp)
3497 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003498 return funcp;
3499}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003500
Denis Vlasenkobc569742009-04-12 20:35:19 +00003501/* Note: takes ownership on name ptr */
3502static struct function *new_function(char *name)
3503{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003504 struct function **funcpp = find_function_slot(name);
3505 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003506
Denys Vlasenko873273d2009-09-12 14:47:41 +02003507 if (funcp != NULL) {
3508 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003509 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3510 if (!cmd) {
3511 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3512 free(funcp->name);
3513 /* Note: if !funcp->body, do not free body_as_string!
3514 * This is a special case of "-F name body" function:
3515 * body_as_string was not malloced! */
3516 if (funcp->body) {
3517 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003518# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003519 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003520# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003521 }
3522 } else {
3523 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3524 cmd->argv[0] = funcp->name;
3525 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003526# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003527 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003528# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003529 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003530 } else {
3531 debug_printf_exec("remembering new function '%s'\n", name);
3532 funcp = *funcpp = xzalloc(sizeof(*funcp));
3533 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003534 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003535
Denis Vlasenkobc569742009-04-12 20:35:19 +00003536 funcp->name = name;
3537 return funcp;
3538}
3539
Denis Vlasenko40e84372009-04-18 11:23:38 +00003540static void unset_func(const char *name)
3541{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003542 struct function **funcpp = find_function_slot(name);
3543 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003544
Denys Vlasenko873273d2009-09-12 14:47:41 +02003545 if (funcp != NULL) {
3546 debug_printf_exec("freeing function '%s'\n", funcp->name);
3547 *funcpp = funcp->next;
3548 /* funcp is unlinked now, deleting it.
3549 * Note: if !funcp->body, the function was created by
3550 * "-F name body", do not free ->body_as_string
3551 * and ->name as they were not malloced. */
3552 if (funcp->body) {
3553 free_pipe_list(funcp->body);
3554 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003555# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003556 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003557# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003558 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003559 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003560 }
3561}
3562
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003563# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003564#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003565 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003566# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003567static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003568 const struct function *funcp,
3569 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003570static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003571 const struct function *funcp,
3572 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003573{
3574# if BB_MMU
3575 int n = 1;
3576
3577 argv[0] = G.global_argv[0];
3578 G.global_argv = argv;
3579 while (*++argv)
3580 n++;
3581 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003582 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003583 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003584 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003585 _exit(n);
3586# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003587 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003588 funcp->body_as_string,
3589 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003590 argv + 1,
3591 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003592# endif
3593}
3594
3595static int run_function(const struct function *funcp, char **argv)
3596{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003597 int rc;
3598 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003599 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003600
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003601 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003602
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003603 /* "we are in function, ok to use return" */
3604 sv_flg = G.flag_return_in_progress;
3605 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003606# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003607 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003608# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003609
Denis Vlasenkobc569742009-04-12 20:35:19 +00003610 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003611# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003612 if (!funcp->body) {
3613 /* Function defined by -F */
3614 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003615 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003616 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003617# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003618 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003619 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003620 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003621
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003622# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003623 {
3624 struct variable *var;
3625 struct variable **var_pp;
3626
3627 var_pp = &G.top_var;
3628 while ((var = *var_pp) != NULL) {
3629 if (var->func_nest_level < G.func_nest_level) {
3630 var_pp = &var->next;
3631 continue;
3632 }
3633 /* Unexport */
3634 if (var->flg_export)
3635 bb_unsetenv(var->varstr);
3636 /* Remove from global list */
3637 *var_pp = var->next;
3638 /* Free */
3639 if (!var->max_len)
3640 free(var->varstr);
3641 free(var);
3642 }
3643 G.func_nest_level--;
3644 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003645# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003646 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003647
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003648 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003649
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003650 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003651}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003652#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003653
3654
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003655#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003656#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003657 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003658#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003659#define exec_builtin(to_free, x, argv) \
3660 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003661#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003662static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003663 const struct built_in_command *x,
3664 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003665static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003666 const struct built_in_command *x,
3667 char **argv)
3668{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003669#if BB_MMU
Denys Vlasenko17323a62010-01-28 01:57:05 +01003670 int rcode = x->b_function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003671 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003672 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003673#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003674 /* On NOMMU, we must never block!
3675 * Example: { sleep 99 | read line; } & echo Ok
3676 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003677 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003678 argv[0],
3679 G.global_argv[0],
3680 G.global_argv + 1,
3681 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003682#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003683}
3684
3685
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003686static void execvp_or_die(char **argv) NORETURN;
3687static void execvp_or_die(char **argv)
3688{
3689 debug_printf_exec("execing '%s'\n", argv[0]);
3690 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3691 execvp(argv[0], argv);
3692 bb_perror_msg("can't execute '%s'", argv[0]);
3693 _exit(127); /* bash compat */
3694}
3695
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003696static void dump_cmd_in_x_mode(char **argv)
3697{
3698 if (G.x_mode && argv) {
3699 /* We want to output the line in one write op */
3700 char *buf, *p;
3701 int len;
3702 int n;
3703
3704 len = 3;
3705 n = 0;
3706 while (argv[n])
3707 len += strlen(argv[n++]) + 1;
3708 buf = xmalloc(len);
3709 buf[0] = '+';
3710 p = buf + 1;
3711 n = 0;
3712 while (argv[n])
3713 p += sprintf(p, " %s", argv[n++]);
3714 *p++ = '\n';
3715 *p = '\0';
3716 fputs(buf, stderr);
3717 free(buf);
3718 }
3719}
3720
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003721#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003722#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3723 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3724#define pseudo_exec(nommu_save, command, argv_expanded) \
3725 pseudo_exec(command, argv_expanded)
3726#endif
3727
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003728/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003729 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003730 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003731 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003732 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003733static void pseudo_exec_argv(nommu_save_t *nommu_save,
3734 char **argv, int assignment_cnt,
3735 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003736static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003737 char **argv, int assignment_cnt,
3738 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003739{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003740 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003741
Denis Vlasenko9504e442008-10-29 01:19:15 +00003742 new_env = expand_assignments(argv, assignment_cnt);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003743 dump_cmd_in_x_mode(new_env);
Denys Vlasenko889550b2010-07-14 19:01:25 +02003744
3745 if (!argv[assignment_cnt]) {
3746 /* Case when we are here: ... | var=val | ...
3747 * (note that we do not exit early, i.e., do not optimize out
3748 * expand_assignments(): think about ... | var=`sleep 1` | ...
3749 */
3750 free_strings(new_env);
3751 _exit(EXIT_SUCCESS);
3752 }
3753
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003754#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003755 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003756 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003757 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003758 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003759#else
3760 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003761 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003762#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02003763
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003764 if (argv_expanded) {
3765 argv = argv_expanded;
3766 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003767 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003768#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003769 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003770#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003771 }
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003772 dump_cmd_in_x_mode(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003773
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003774#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3775 if (strchr(argv[0], '/') != NULL)
3776 goto skip;
3777#endif
3778
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003779 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003780 * Depending on context, this might be redundant. But it's
3781 * easier to waste a few CPU cycles than it is to figure out
3782 * if this is one of those cases.
3783 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003784 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003785 /* On NOMMU, it is more expensive to re-execute shell
3786 * just in order to run echo or test builtin.
3787 * It's better to skip it here and run corresponding
3788 * non-builtin later. */
3789 const struct built_in_command *x;
3790 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003791 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003792 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003793 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003794 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003795#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003796 /* Check if the command matches any functions */
3797 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003798 const struct function *funcp = find_function(argv[0]);
3799 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003800 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003801 }
3802 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003803#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003804
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003805#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003806 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003807 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003808 int a = find_applet_by_name(argv[0]);
3809 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003810# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003811 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003812 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003813 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003814 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003815# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003816 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003817 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003818 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3819 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003820 /* If they called chroot or otherwise made the binary no longer
3821 * executable, fall through */
3822 }
3823 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003824#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003825
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003826#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003827 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003828#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003829 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003830}
3831
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003832/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003833 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003834static void pseudo_exec(nommu_save_t *nommu_save,
3835 struct command *command,
3836 char **argv_expanded) NORETURN;
3837static void pseudo_exec(nommu_save_t *nommu_save,
3838 struct command *command,
3839 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003840{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003841 if (command->argv) {
3842 pseudo_exec_argv(nommu_save, command->argv,
3843 command->assignment_cnt, argv_expanded);
3844 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003845
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003846 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003847 /* Cases when we are here:
3848 * ( list )
3849 * { list } &
3850 * ... | ( list ) | ...
3851 * ... | { list } | ...
3852 */
3853#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003854 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003855 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003856 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003857 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003858 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003859 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003860 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003861#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003862 re_execute_shell(&nommu_save->argv_from_re_execing,
3863 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003864 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003865 G.global_argv + 1,
3866 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003867#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003868 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003869
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003870 /* Case when we are here: ... | >file */
3871 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003872 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003873}
3874
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003875#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003876static const char *get_cmdtext(struct pipe *pi)
3877{
3878 char **argv;
3879 char *p;
3880 int len;
3881
3882 /* This is subtle. ->cmdtext is created only on first backgrounding.
3883 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003884 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003885 if (pi->cmdtext)
3886 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003887 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003888 if (!argv || !argv[0]) {
3889 pi->cmdtext = xzalloc(1);
3890 return pi->cmdtext;
3891 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003892
3893 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003894 do {
3895 len += strlen(*argv) + 1;
3896 } while (*++argv);
3897 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003898 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003899 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003900 do {
3901 len = strlen(*argv);
3902 memcpy(p, *argv, len);
3903 p += len;
3904 *p++ = ' ';
3905 } while (*++argv);
3906 p[-1] = '\0';
3907 return pi->cmdtext;
3908}
3909
Eric Andersenbafd94f2001-05-02 16:11:59 +00003910static void insert_bg_job(struct pipe *pi)
3911{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003912 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003913 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003914
3915 /* Linear search for the ID of the job to use */
3916 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003917 for (job = G.job_list; job; job = job->next)
3918 if (job->jobid >= pi->jobid)
3919 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003920
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003921 /* Add job to the list of running jobs */
3922 jobp = &G.job_list;
3923 while ((job = *jobp) != NULL)
3924 jobp = &job->next;
3925 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003926
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003927 *job = *pi; /* physical copy */
3928 job->next = NULL;
3929 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3930 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003931 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003932 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003933 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003934 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003935 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003936
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003937 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003938 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3939 /* Last command's pid goes to $! */
3940 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3941 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003942}
3943
Eric Andersenbafd94f2001-05-02 16:11:59 +00003944static void remove_bg_job(struct pipe *pi)
3945{
3946 struct pipe *prev_pipe;
3947
Denis Vlasenko87a86552008-07-29 19:43:10 +00003948 if (pi == G.job_list) {
3949 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003950 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003951 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003952 while (prev_pipe->next != pi)
3953 prev_pipe = prev_pipe->next;
3954 prev_pipe->next = pi->next;
3955 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003956 if (G.job_list)
3957 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003958 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003959 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003960}
Eric Andersen028b65b2001-06-28 01:10:11 +00003961
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003962/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003963static void delete_finished_bg_job(struct pipe *pi)
3964{
3965 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003966 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003967 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003968 free(pi);
3969}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003970#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003971
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003972/* Check to see if any processes have exited -- if they
3973 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003974static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003975{
Eric Andersenc798b072001-06-22 06:23:03 +00003976 int attributes;
3977 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003978#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003979 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003980#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003981 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003982 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003983
Denis Vlasenkod5762932009-03-31 11:22:57 +00003984 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3985
Eric Andersenc798b072001-06-22 06:23:03 +00003986 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003987 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003988 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003989
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003990 errno = 0;
3991#if ENABLE_HUSH_FAST
3992 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3993//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3994//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003995 /* There was neither fork nor SIGCHLD since last waitpid */
3996 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003997 if (!G.we_have_children) {
3998 errno = ECHILD;
3999 return -1;
4000 }
4001 if (fg_pipe == NULL) { /* is WNOHANG set? */
4002 /* We have children, but they did not exit
4003 * or stop yet (we saw no SIGCHLD) */
4004 return 0;
4005 }
4006 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4007 }
4008#endif
4009
Denis Vlasenko1359da62007-04-21 23:27:30 +00004010/* Do we do this right?
4011 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004012 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00004013 * [3]+ Stopped sleep 20 | false
4014 * bash-3.00# echo $?
4015 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004016 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00004017 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004018 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004019 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004020 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004021 int dead;
4022
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004023#if ENABLE_HUSH_FAST
4024 i = G.count_SIGCHLD;
4025#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004026 childpid = waitpid(-1, &status, attributes);
4027 if (childpid <= 0) {
4028 if (childpid && errno != ECHILD)
4029 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004030#if ENABLE_HUSH_FAST
4031 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004032 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004033 G.handled_SIGCHLD = i;
4034//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4035 }
4036#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004037 break;
4038 }
4039 dead = WIFEXITED(status) || WIFSIGNALED(status);
4040
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00004041#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00004042 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004043 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004044 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4045 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004046 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004047 childpid, WTERMSIG(status), WEXITSTATUS(status));
4048 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004049 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004050 childpid, WEXITSTATUS(status));
4051#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004052 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00004053 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004054 for (i = 0; i < fg_pipe->num_cmds; i++) {
4055 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4056 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004057 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004058 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004059 fg_pipe->cmds[i].pid = 0;
4060 fg_pipe->alive_cmds--;
4061 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004062 /* last process gives overall exitstatus */
4063 rcode = WEXITSTATUS(status);
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004064 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00004065 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004066 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00004067 */
4068 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00004069 int sig = WTERMSIG(status);
4070 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004071 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4072 * Maybe we need to use sig | 128? */
4073 rcode = sig + 128;
Denis Vlasenko40e84372009-04-18 11:23:38 +00004074 }
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004075 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00004076 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004077 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004078 fg_pipe->cmds[i].is_stopped = 1;
4079 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00004080 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004081 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4082 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4083 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004084 /* All processes in fg pipe have exited or stopped */
4085/* Note: *non-interactive* bash does not continue if all processes in fg pipe
4086 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4087 * and "killall -STOP cat" */
4088 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004089#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004090 if (fg_pipe->alive_cmds)
4091 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004092#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004093 return rcode;
4094 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02004095 if (!fg_pipe->alive_cmds)
4096 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004097 }
4098 /* There are still running processes in the fg pipe */
4099 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00004100 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004101 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00004102 }
4103
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004104#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004105 /* We asked to wait for bg or orphaned children */
4106 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004107 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004108 for (i = 0; i < pi->num_cmds; i++) {
4109 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004110 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00004111 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00004112 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004113 /* Happens when shell is used as init process (init=/bin/sh) */
4114 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004115 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00004116
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004117 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00004118 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00004119 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004120 pi->cmds[i].pid = 0;
4121 pi->alive_cmds--;
4122 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004123 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00004124 printf(JOB_STATUS_FORMAT, pi->jobid,
4125 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004126 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004127 }
4128 } else {
4129 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004130 pi->cmds[i].is_stopped = 1;
4131 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004132 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004133#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004134 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004135
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004136 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00004137}
4138
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004139#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00004140static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4141{
4142 pid_t p;
4143 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04004144 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004145 /* Job finished, move the shell to the foreground */
4146 p = getpgrp(); /* our process group id */
4147 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4148 tcsetpgrp(G_interactive_fd, p);
4149 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00004150 return rcode;
4151}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004152#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00004153
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004154/* Start all the jobs, but don't wait for anything to finish.
4155 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00004156 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00004157 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00004158 * to finish to determine the exit status of the pipe. If the pipe
4159 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00004160 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00004161 * return value.
4162 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00004163 * Returns -1 only if started some children. IOW: we have to
4164 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00004165 *
4166 * The only case when we do not need to [v]fork is when the pipe
4167 * is single, non-backgrounded, non-subshell command. Examples:
4168 * cmd ; ... { list } ; ...
4169 * cmd && ... { list } && ...
4170 * cmd || ... { list } || ...
4171 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4172 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004173 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00004174 *
4175 * Cases when we must fork:
4176 * non-single: cmd | cmd
4177 * backgrounded: cmd & { list } &
4178 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00004179 */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02004180static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004181{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004182 static const char *const null_ptr = NULL;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004183
4184 int cmd_no;
4185 int next_infd;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004186 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004187 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004188 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004189 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004190 /* it is not always needed, but we aim to smaller code */
4191 int squirrel[] = { -1, -1, -1 };
4192 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004193
Denis Vlasenko552433b2009-04-04 19:29:21 +00004194 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004195 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004196
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004197 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004198 pi->stopped_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004199 command = &pi->cmds[0];
Denis Vlasenko552433b2009-04-04 19:29:21 +00004200 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004201
Denis Vlasenko552433b2009-04-04 19:29:21 +00004202 if (pi->num_cmds != 1
4203 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004204 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00004205 ) {
4206 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004207 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004208
Denis Vlasenko552433b2009-04-04 19:29:21 +00004209 pi->alive_cmds = 1;
4210
4211 debug_printf_exec(": group:%p argv:'%s'\n",
4212 command->group, command->argv ? command->argv[0] : "NONE");
4213
4214 if (command->group) {
4215#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004216 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004217 /* "executing" func () { list } */
4218 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004219
Denis Vlasenkobc569742009-04-12 20:35:19 +00004220 funcp = new_function(command->argv[0]);
4221 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004222 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004223# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004224 funcp->body_as_string = command->group_as_string;
4225 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004226# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004227 command->group = NULL;
4228 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00004229 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4230 funcp->parent_cmd = command;
4231 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004232
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004233 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4234 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00004235 return EXIT_SUCCESS;
4236 }
4237#endif
4238 /* { list } */
4239 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004240 rcode = 1; /* exitcode if redir failed */
4241 if (setup_redirects(command, squirrel) == 0) {
4242 debug_printf_exec(": run_list\n");
4243 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004244 }
Eric Andersen04407e52001-06-07 16:42:05 +00004245 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004246 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004247 debug_leave();
4248 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004249 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004250 }
4251
Denis Vlasenko552433b2009-04-04 19:29:21 +00004252 argv = command->argv ? command->argv : (char **) &null_ptr;
4253 {
4254 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004255#if ENABLE_HUSH_FUNCTIONS
4256 const struct function *funcp;
4257#else
4258 enum { funcp = 0 };
4259#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004260 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004261 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004262
Denis Vlasenko552433b2009-04-04 19:29:21 +00004263 if (argv[command->assignment_cnt] == NULL) {
4264 /* Assignments, but no command */
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004265 /* Ensure redirects take effect (that is, create files).
4266 * Try "a=t >file": */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004267 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004268 restore_redirects(squirrel);
4269 /* Set shell variables */
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004270 if (G.x_mode)
4271 bb_putchar_stderr('+');
Denis Vlasenko552433b2009-04-04 19:29:21 +00004272 while (*argv) {
4273 p = expand_string_to_string(*argv);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004274 if (G.x_mode)
4275 fprintf(stderr, " %s", p);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004276 debug_printf_exec("set shell var:'%s'->'%s'\n",
4277 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004278 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004279 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004280 }
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004281 if (G.x_mode)
4282 bb_putchar_stderr('\n');
Denys Vlasenkob3389de2010-07-15 12:33:37 +02004283 /* Redirect error sets $? to 1. Otherwise,
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004284 * if evaluating assignment value set $?, retain it.
4285 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4286 if (rcode == 0)
4287 rcode = G.last_exitcode;
Denis Vlasenko552433b2009-04-04 19:29:21 +00004288 /* Do we need to flag set_local_var() errors?
4289 * "assignment to readonly var" and "putenv error"
4290 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004291 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004292 debug_leave();
4293 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004294 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00004295 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004296
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004297 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004298 if (0) {}
4299#if ENABLE_HUSH_BASH_COMPAT
4300 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004301 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4302 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004303#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004304#ifdef CMD_SINGLEWORD_NOGLOB_COND
4305 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4306 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4307
4308 }
4309#endif
4310 else {
4311 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4312 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004313
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004314 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004315 if (!argv_expanded[0]) {
Denys Vlasenko385cc592010-01-12 06:47:39 +01004316 free(argv_expanded);
Mike Frysinger28736c32009-10-18 01:11:45 -04004317 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004318 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004319 }
4320
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004321 x = find_builtin(argv_expanded[0]);
4322#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004323 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004324 if (!x)
4325 funcp = find_function(argv_expanded[0]);
4326#endif
4327 if (x || funcp) {
4328 if (!funcp) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01004329 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004330 debug_printf("exec with redirects only\n");
4331 rcode = setup_redirects(command, NULL);
4332 goto clean_up_and_ret1;
4333 }
Eric Andersen25f27032001-04-26 23:22:31 +00004334 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004335 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004336 * This is perfect for work that comes after exec().
4337 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004338 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004339 rcode = setup_redirects(command, squirrel);
4340 if (rcode == 0) {
4341 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004342 dump_cmd_in_x_mode(new_env);
4343 dump_cmd_in_x_mode(argv_expanded);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004344 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004345 if (!funcp) {
4346 debug_printf_exec(": builtin '%s' '%s'...\n",
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004347 x->b_cmd, argv_expanded[1]);
Denys Vlasenko17323a62010-01-28 01:57:05 +01004348 rcode = x->b_function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004349 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004350 }
4351#if ENABLE_HUSH_FUNCTIONS
4352 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004353# if ENABLE_HUSH_LOCAL
4354 struct variable **sv;
4355 sv = G.shadowed_vars_pp;
4356 G.shadowed_vars_pp = &old_vars;
4357# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004358 debug_printf_exec(": function '%s' '%s'...\n",
4359 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004360 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004361# if ENABLE_HUSH_LOCAL
4362 G.shadowed_vars_pp = sv;
4363# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004364 }
4365#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004366 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004367 clean_up_and_ret:
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004368 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004369 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004370 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004371 clean_up_and_ret1:
4372 free(argv_expanded);
4373 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004374 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004375 debug_printf_exec("run_pipe return %d\n", rcode);
4376 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004377 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004378
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004379 if (ENABLE_FEATURE_SH_STANDALONE) {
4380 int n = find_applet_by_name(argv_expanded[0]);
4381 if (n >= 0 && APPLET_IS_NOFORK(n)) {
4382 rcode = setup_redirects(command, squirrel);
4383 if (rcode == 0) {
4384 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004385 dump_cmd_in_x_mode(new_env);
4386 dump_cmd_in_x_mode(argv_expanded);
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004387 old_vars = set_vars_and_save_old(new_env);
4388 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4389 argv_expanded[0], argv_expanded[1]);
4390 rcode = run_nofork_applet(n, argv_expanded);
4391 }
4392 goto clean_up_and_ret;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004393 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004394 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00004395 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004396 }
4397
Denis Vlasenko552433b2009-04-04 19:29:21 +00004398 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004399 /* NB: argv_expanded may already be created, and that
4400 * might include `cmd` runs! Do not rerun it! We *must*
4401 * use argv_expanded if it's non-NULL */
4402
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004403 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004404 pi->alive_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004405 next_infd = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004406
Denys Vlasenko889550b2010-07-14 19:01:25 +02004407 cmd_no = 0;
4408 while (cmd_no < pi->num_cmds) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004409 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004410#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004411 volatile nommu_save_t nommu_save;
4412 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004413 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004414 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004415 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004416#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02004417 command = &pi->cmds[cmd_no];
4418 cmd_no++;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004419 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004420 debug_printf_exec(": pipe member '%s' '%s'...\n",
4421 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004422 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004423 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004424 }
Eric Andersen25f27032001-04-26 23:22:31 +00004425
4426 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004427 pipefds.rd = 0;
4428 pipefds.wr = 1;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004429 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004430 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004431
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004432 command->pid = BB_MMU ? fork() : vfork();
4433 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004434#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004435 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004436 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004437
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004438 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004439 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004440 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004441 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004442 pgrp = pi->pgrp;
4443 if (pgrp < 0) /* true for 1st process only */
4444 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004445 if (setpgid(0, pgrp) == 0
4446 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004447 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004448 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004449 /* We do it in *every* child, not just first,
4450 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004451 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004452 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004453 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004454#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004455 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4456 /* 1st cmd in backgrounded pipe
4457 * should have its stdin /dev/null'ed */
4458 close(0);
4459 if (open(bb_dev_null, O_RDONLY))
4460 xopen("/", O_RDONLY);
4461 } else {
Denys Vlasenko889550b2010-07-14 19:01:25 +02004462 xmove_fd(next_infd, 0);
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004463 }
4464 xmove_fd(pipefds.wr, 1);
4465 if (pipefds.rd > 1)
4466 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004467 /* Like bash, explicit redirects override pipes,
4468 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004469 if (setup_redirects(command, NULL))
4470 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004471
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004472 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004473 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4474
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004475 /* Stores to nommu_save list of env vars putenv'ed
4476 * (NOMMU, on MMU we don't need that) */
4477 /* cast away volatility... */
4478 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004479 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004480 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004481
Denis Vlasenkof9375282009-04-05 19:13:39 +00004482 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004483#if ENABLE_HUSH_FAST
4484 G.count_SIGCHLD++;
4485//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4486#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004487 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004488#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004489 /* Clean up after vforked child */
4490 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004491 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004492 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004493 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004494#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004495 free(argv_expanded);
4496 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004497 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004498 /* Clearly indicate, was it fork or vfork */
Pascal Bellard926031b2010-07-04 15:32:38 +02004499 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004500 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004501 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004502#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004503 /* Second and next children need to know pid of first one */
4504 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004505 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004506#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004507 }
Eric Andersen25f27032001-04-26 23:22:31 +00004508
Denys Vlasenko889550b2010-07-14 19:01:25 +02004509 if (cmd_no > 1)
4510 close(next_infd);
4511 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004512 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004513 /* Pass read (output) pipe end to next iteration */
Denys Vlasenko889550b2010-07-14 19:01:25 +02004514 next_infd = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004515 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004516
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004517 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004518 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004519 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4520 return 1;
4521 }
4522
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004523 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004524 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004525 return -1;
4526}
4527
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004528#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004529static void debug_print_tree(struct pipe *pi, int lvl)
4530{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004531 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004532 [PIPE_SEQ] = "SEQ",
4533 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004534 [PIPE_OR ] = "OR" ,
4535 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004536 };
4537 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004538 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004539# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004540 [RES_IF ] = "IF" ,
4541 [RES_THEN ] = "THEN" ,
4542 [RES_ELIF ] = "ELIF" ,
4543 [RES_ELSE ] = "ELSE" ,
4544 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004545# endif
4546# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004547 [RES_FOR ] = "FOR" ,
4548 [RES_WHILE] = "WHILE",
4549 [RES_UNTIL] = "UNTIL",
4550 [RES_DO ] = "DO" ,
4551 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004552# endif
4553# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004554 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004555# endif
4556# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004557 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004558 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004559 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004560 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004561 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004562# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004563 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004564 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004565 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004566 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004567 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004568 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004569 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004570# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004571 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004572# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004573 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004574
4575 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004576
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004577 pin = 0;
4578 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004579 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4580 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004581 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004582 while (prn < pi->num_cmds) {
4583 struct command *command = &pi->cmds[prn];
4584 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004585
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004586 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004587 lvl*2, "", prn,
4588 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004589 if (command->group) {
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004590 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004591 CMDTYPE[command->cmd_type],
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004592 argv
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004593# if !BB_MMU
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004594 , " group_as_string:", command->group_as_string
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004595# else
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004596 , "", ""
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004597# endif
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004598 );
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004599 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004600 prn++;
4601 continue;
4602 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004603 if (argv) while (*argv) {
4604 fprintf(stderr, " '%s'", *argv);
4605 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004606 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004607 fprintf(stderr, "\n");
4608 prn++;
4609 }
4610 pi = pi->next;
4611 pin++;
4612 }
4613}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004614#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004615
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004616/* NB: called by pseudo_exec, and therefore must not modify any
4617 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004618static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004619{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004620#if ENABLE_HUSH_CASE
4621 char *case_word = NULL;
4622#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004623#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004624 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004625 char **for_lcur = NULL;
4626 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004627#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004628 smallint last_followup;
4629 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004630#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004631 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004632#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004633 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004634#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004635#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004636 smallint rword; /* enum reserved_style */
4637 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004638#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004639
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004640 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004641 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004642
Denis Vlasenko06810332007-05-21 23:30:54 +00004643#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004644 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004645 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4646 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004647 continue;
4648 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004649 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004650 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004651 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004652 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004653 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004654 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004655 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004656 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004657 continue;
4658 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004659 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4660 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004661 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004662 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004663 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004664 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004665 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004666 }
4667 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004668#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004669
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004670 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004671 * in order to return, no direct "return" statements please.
4672 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004673
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004674#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004675 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004676#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004677
Denis Vlasenko0e151382009-04-06 18:40:31 +00004678#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004679 rword = RES_NONE;
4680 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004681#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004682 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004683 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004684
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004685 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004686 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004687 if (G.flag_SIGINT)
4688 break;
4689
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004690 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004691 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4692 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004693#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004694 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004695 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004696 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004697 /* start of a loop: remember where loop starts */
4698 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004699 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004700 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004701#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004702 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004703 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004704 if ((rcode == 0 && last_followup == PIPE_OR)
4705 || (rcode != 0 && last_followup == PIPE_AND)
4706 ) {
4707 /* It is "<true> || CMD" or "<false> && CMD"
4708 * and we should not execute CMD */
4709 debug_printf_exec("skipped cmd because of || or &&\n");
4710 last_followup = pi->followup;
4711 continue;
4712 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004713 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004714 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004715 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004716#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004717 if (cond_code) {
4718 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004719 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004720 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004721 /* "if <false> THEN cmd": skip cmd */
4722 continue;
4723 }
4724 } else {
4725 if (rword == RES_ELSE || rword == RES_ELIF) {
4726 /* "if <true> then ... ELSE/ELIF cmd":
4727 * skip cmd and all following ones */
4728 break;
4729 }
4730 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004731#endif
4732#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004733 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004734 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004735 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004736
4737 static const char encoded_dollar_at[] ALIGN1 = {
4738 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4739 }; /* encoded representation of "$@" */
4740 static const char *const encoded_dollar_at_argv[] = {
4741 encoded_dollar_at, NULL
4742 }; /* argv list with one element: "$@" */
4743 char **vals;
4744
4745 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004746 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004747 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004748 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004749 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004750 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004751 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004752 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004753 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004754 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004755 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004756 debug_print_strings("for_list made from", vals);
4757 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004758 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004759 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004760 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004761 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004762 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004763 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004764 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004765 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004766 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004767 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004768 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004769 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004770 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 +02004771 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004772 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004773 if (rword == RES_IN) {
4774 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4775 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004776 if (rword == RES_DONE) {
4777 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004778 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004779#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004780#if ENABLE_HUSH_CASE
4781 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004782 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004783 continue;
4784 }
4785 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004786 char **argv;
4787
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004788 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4789 break;
4790 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004791 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004792 while (*argv) {
4793 char *pattern = expand_string_to_string(*argv);
4794 /* TODO: which FNM_xxx flags to use? */
4795 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4796 free(pattern);
4797 if (cond_code == 0) { /* match! we will execute this branch */
4798 free(case_word); /* make future "word)" stop */
4799 case_word = NULL;
4800 break;
4801 }
4802 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004803 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004804 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004805 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004806 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004807 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004808 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004809 }
4810#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004811 /* Just pressing <enter> in shell should check for jobs.
4812 * OTOH, in non-interactive shell this is useless
4813 * and only leads to extra job checks */
4814 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004815 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004816 goto check_jobs_and_continue;
4817 continue;
4818 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004819
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004820 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004821 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004822 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004823 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004824 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004825 {
4826 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004827#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004828 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004829#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004830 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4831 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004832 /* We ran a builtin, function, or group.
4833 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004834 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004835 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004836 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004837 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004838#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004839 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004840 if (G.flag_break_continue) {
4841 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004842 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004843 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004844 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004845 G.depth_break_continue--;
4846 if (G.depth_break_continue == 0)
4847 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004848 /* else: e.g. "continue 2" should *break* once, *then* continue */
4849 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004850 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004851 goto check_jobs_and_break;
4852 /* "continue": simulate end of loop */
4853 rword = RES_DONE;
4854 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004855 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004856#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004857#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004858 if (G.flag_return_in_progress == 1) {
4859 /* same as "goto check_jobs_and_break" */
4860 checkjobs(NULL);
4861 break;
4862 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004863#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004864 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004865 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004866 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004867 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4868 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004869 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004870#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004871 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004872 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004873#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004874 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004875 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004876 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004877#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004878 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004879 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004880 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004881 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004882 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004883 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004884#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004885 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004886 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004887 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004888 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004889 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004890 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004891 }
4892 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004893
4894 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004895#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004896 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004897 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004898#endif
4899#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004900 /* Beware of "while false; true; do ..."! */
4901 if (pi->next && pi->next->res_word == RES_DO) {
4902 if (rword == RES_WHILE) {
4903 if (rcode) {
4904 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004905 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004906 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4907 goto check_jobs_and_break;
4908 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004909 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004910 if (rword == RES_UNTIL) {
4911 if (!rcode) {
4912 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004913 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004914 checkjobs(NULL);
4915 break;
4916 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004917 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004918 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004919#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004920
4921 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004922 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004923 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004924
4925#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004926 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004927#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004928#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004929 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004930 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004931 free(for_list);
4932#endif
4933#if ENABLE_HUSH_CASE
4934 free(case_word);
4935#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004936 debug_leave();
4937 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004938 return rcode;
4939}
4940
Eric Andersen25f27032001-04-26 23:22:31 +00004941/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004942static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004943{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004944 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004945 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004946 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004947 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004948 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004949 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004950 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004951 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004952 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004953 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004954 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004955 return rcode;
4956}
4957
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004958
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004959static struct pipe *new_pipe(void)
4960{
Eric Andersen25f27032001-04-26 23:22:31 +00004961 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004962 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004963 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004964 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004965 return pi;
4966}
4967
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004968/* Command (member of a pipe) is complete, or we start a new pipe
4969 * if ctx->command is NULL.
4970 * No errors possible here.
4971 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004972static int done_command(struct parse_context *ctx)
4973{
4974 /* The command is really already in the pipe structure, so
4975 * advance the pipe counter and make a new, null command. */
4976 struct pipe *pi = ctx->pipe;
4977 struct command *command = ctx->command;
4978
4979 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004980 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004981 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004982 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004983 }
4984 pi->num_cmds++;
4985 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004986 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004987 } else {
4988 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4989 }
4990
4991 /* Only real trickiness here is that the uncommitted
4992 * command structure is not counted in pi->num_cmds. */
4993 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004994 ctx->command = command = &pi->cmds[pi->num_cmds];
4995 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004996 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004997 return pi->num_cmds; /* used only for 0/nonzero check */
4998}
4999
5000static void done_pipe(struct parse_context *ctx, pipe_style type)
5001{
5002 int not_null;
5003
5004 debug_printf_parse("done_pipe entered, followup %d\n", type);
5005 /* Close previous command */
5006 not_null = done_command(ctx);
5007 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005008#if HAS_KEYWORDS
5009 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5010 ctx->ctx_inverted = 0;
5011 ctx->pipe->res_word = ctx->ctx_res_w;
5012#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005013
5014 /* Without this check, even just <enter> on command line generates
5015 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005016 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005017 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00005018#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005019 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00005020#endif
5021#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005022 || ctx->ctx_res_w == RES_DONE
5023 || ctx->ctx_res_w == RES_FOR
5024 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00005025#endif
5026#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005027 || ctx->ctx_res_w == RES_ESAC
5028#endif
5029 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005030 struct pipe *new_p;
5031 debug_printf_parse("done_pipe: adding new pipe: "
5032 "not_null:%d ctx->ctx_res_w:%d\n",
5033 not_null, ctx->ctx_res_w);
5034 new_p = new_pipe();
5035 ctx->pipe->next = new_p;
5036 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005037 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005038 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005039 * This is used to control execution.
5040 * RES_FOR and RES_IN are NOT sticky (needed to support
5041 * cases where variable or value happens to match a keyword):
5042 */
5043#if ENABLE_HUSH_LOOPS
5044 if (ctx->ctx_res_w == RES_FOR
5045 || ctx->ctx_res_w == RES_IN)
5046 ctx->ctx_res_w = RES_NONE;
5047#endif
5048#if ENABLE_HUSH_CASE
5049 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005050 ctx->ctx_res_w = RES_CASE_BODY;
5051 if (ctx->ctx_res_w == RES_CASE)
5052 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005053#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005054 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005055 /* Create the memory for command, roughly:
5056 * ctx->pipe->cmds = new struct command;
5057 * ctx->command = &ctx->pipe->cmds[0];
5058 */
5059 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005060 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005061 }
5062 debug_printf_parse("done_pipe return\n");
5063}
5064
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005065static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005066{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005067 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00005068 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005069 /* Create the memory for command, roughly:
5070 * ctx->pipe->cmds = new struct command;
5071 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005072 */
5073 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005074}
5075
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005076/* If a reserved word is found and processed, parse context is modified
5077 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00005078 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005079#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005080struct reserved_combo {
5081 char literal[6];
5082 unsigned char res;
5083 unsigned char assignment_flag;
5084 int flag;
5085};
5086enum {
5087 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005088# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005089 FLAG_IF = (1 << RES_IF ),
5090 FLAG_THEN = (1 << RES_THEN ),
5091 FLAG_ELIF = (1 << RES_ELIF ),
5092 FLAG_ELSE = (1 << RES_ELSE ),
5093 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005094# endif
5095# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005096 FLAG_FOR = (1 << RES_FOR ),
5097 FLAG_WHILE = (1 << RES_WHILE),
5098 FLAG_UNTIL = (1 << RES_UNTIL),
5099 FLAG_DO = (1 << RES_DO ),
5100 FLAG_DONE = (1 << RES_DONE ),
5101 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005102# endif
5103# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005104 FLAG_MATCH = (1 << RES_MATCH),
5105 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005106# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005107 FLAG_START = (1 << RES_XXXX ),
5108};
5109
5110static const struct reserved_combo* match_reserved_word(o_string *word)
5111{
Eric Andersen25f27032001-04-26 23:22:31 +00005112 /* Mostly a list of accepted follow-up reserved words.
5113 * FLAG_END means we are done with the sequence, and are ready
5114 * to turn the compound list into a command.
5115 * FLAG_START means the word must start a new compound list.
5116 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005117 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005118# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005119 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5120 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5121 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5122 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5123 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5124 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005125# endif
5126# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005127 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5128 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5129 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5130 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5131 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5132 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005133# endif
5134# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005135 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5136 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005137# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005138 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005139 const struct reserved_combo *r;
5140
5141 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5142 if (strcmp(word->data, r->literal) == 0)
5143 return r;
5144 }
5145 return NULL;
5146}
Denis Vlasenkobb929512009-04-16 10:59:40 +00005147/* Return 0: not a keyword, 1: keyword
5148 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005149static int reserved_word(o_string *word, struct parse_context *ctx)
5150{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005151# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005152 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005153 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005154 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005155# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005156 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005157
Denis Vlasenkobb929512009-04-16 10:59:40 +00005158 if (word->o_quoted)
5159 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005160 r = match_reserved_word(word);
5161 if (!r)
5162 return 0;
5163
5164 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005165# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005166 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5167 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005168 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005169 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005170# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005171 if (r->flag == 0) { /* '!' */
5172 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005173 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00005174 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00005175 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005176 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005177 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005178 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005179 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005180 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005181
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005182 old = xmalloc(sizeof(*old));
5183 debug_printf_parse("push stack %p\n", old);
5184 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005185 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005186 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005187 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005188 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005189 ctx->ctx_res_w = RES_SNTX;
5190 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005191 } else {
5192 /* "{...} fi" is ok. "{...} if" is not
5193 * Example:
5194 * if { echo foo; } then { echo bar; } fi */
5195 if (ctx->command->group)
5196 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005197 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00005198
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005199 ctx->ctx_res_w = r->res;
5200 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005201 word->o_assignment = r->assignment_flag;
5202
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005203 if (ctx->old_flag & FLAG_END) {
5204 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005205
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005206 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005207 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005208 old = ctx->stack;
5209 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005210 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005211# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005212 o_addstr(&old->as_string, ctx->as_string.data);
5213 o_free_unsafe(&ctx->as_string);
5214 old->command->group_as_string = xstrdup(old->as_string.data);
5215 debug_printf_parse("pop, remembering as:'%s'\n",
5216 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005217# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005218 *ctx = *old; /* physical copy */
5219 free(old);
5220 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005221 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005222}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005223#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00005224
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005225/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005226 * Normal return is 0. Syntax errors return 1.
5227 * Note: on return, word is reset, but not o_free'd!
5228 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005229static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005230{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005231 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00005232
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005233 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005234 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005235 debug_printf_parse("done_word return 0: true null, ignored\n");
5236 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005237 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005238
Eric Andersen25f27032001-04-26 23:22:31 +00005239 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005240 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5241 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005242 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5243 * "2.7 Redirection
5244 * ...the word that follows the redirection operator
5245 * shall be subjected to tilde expansion, parameter expansion,
5246 * command substitution, arithmetic expansion, and quote
5247 * removal. Pathname expansion shall not be performed
5248 * on the word by a non-interactive shell; an interactive
5249 * shell may perform it, but shall do so only when
5250 * the expansion would result in one word."
5251 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005252 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005253 /* Cater for >\file case:
5254 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5255 * Same with heredocs:
5256 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5257 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005258 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5259 unbackslash(ctx->pending_redirect->rd_filename);
5260 /* Is it <<"HEREDOC"? */
5261 if (word->o_quoted) {
5262 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5263 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005264 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005265 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005266 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00005267 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005268 /* If this word wasn't an assignment, next ones definitely
5269 * can't be assignments. Even if they look like ones. */
5270 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5271 && word->o_assignment != WORD_IS_KEYWORD
5272 ) {
5273 word->o_assignment = NOT_ASSIGNMENT;
5274 } else {
5275 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5276 command->assignment_cnt++;
5277 word->o_assignment = MAYBE_ASSIGNMENT;
5278 }
5279
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005280#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005281# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00005282 if (ctx->ctx_dsemicolon
5283 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5284 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00005285 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005286 /* ctx->ctx_res_w = RES_MATCH; */
5287 ctx->ctx_dsemicolon = 0;
5288 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005289# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005290 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005291# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005292 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5293 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005294# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005295# if ENABLE_HUSH_CASE
5296 && ctx->ctx_res_w != RES_CASE
5297# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005298 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005299 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005300 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005301 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005302 debug_printf_parse("done_word return %d\n",
5303 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005304 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005305 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005306# ifdef CMD_SINGLEWORD_NOGLOB_COND
5307 if (strcmp(word->data, "export") == 0
5308# if ENABLE_HUSH_LOCAL
5309 || strcmp(word->data, "local") == 0
5310# endif
5311 ) {
5312 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5313 } else
5314# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005315# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005316 if (strcmp(word->data, "[[") == 0) {
5317 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5318 }
5319 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005320# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005321 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005322#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005323 if (command->group) {
5324 /* "{ echo foo; } echo bar" - bad */
5325 syntax_error_at(word->data);
5326 debug_printf_parse("done_word return 1: syntax error, "
5327 "groups and arglists don't mix\n");
5328 return 1;
5329 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005330 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005331 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5332 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005333 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005334 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005335 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005336 char *p = word->data;
5337 while (p[0] == SPECIAL_VAR_SYMBOL
5338 && (p[1] & 0x7f) == '@'
5339 && p[2] == SPECIAL_VAR_SYMBOL
5340 ) {
5341 p += 3;
5342 }
5343 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005344 /* saw no "$@", or not only "$@" but some
5345 * real text is there too */
5346 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005347 * e.g. "", $empty"" etc to not disappear */
5348 o_addchr(word, SPECIAL_VAR_SYMBOL);
5349 o_addchr(word, SPECIAL_VAR_SYMBOL);
5350 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005351 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005352 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005353 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005354 }
Eric Andersen25f27032001-04-26 23:22:31 +00005355
Denis Vlasenko06810332007-05-21 23:30:54 +00005356#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005357 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005358 if (word->o_quoted
5359 || !is_well_formed_var_name(command->argv[0], '\0')
5360 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005361 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005362 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005363 return 1;
5364 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005365 /* Force FOR to have just one word (variable name) */
5366 /* NB: basically, this makes hush see "for v in ..."
5367 * syntax as if it is "for v; in ...". FOR and IN become
5368 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005369 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005370 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005371#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005372#if ENABLE_HUSH_CASE
5373 /* Force CASE to have just one word */
5374 if (ctx->ctx_res_w == RES_CASE) {
5375 done_pipe(ctx, PIPE_SEQ);
5376 }
5377#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005378
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005379 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005380
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005381 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005382 return 0;
5383}
5384
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005385
5386/* Peek ahead in the input to find out if we have a "&n" construct,
5387 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005388 * Return:
5389 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5390 * REDIRFD_SYNTAX_ERR if syntax error,
5391 * REDIRFD_TO_FILE if no & was seen,
5392 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005393 */
5394#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005395#define parse_redir_right_fd(as_string, input) \
5396 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005397#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005398static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005399{
5400 int ch, d, ok;
5401
5402 ch = i_peek(input);
5403 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005404 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005405
5406 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005407 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005408 ch = i_peek(input);
5409 if (ch == '-') {
5410 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005411 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005412 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005413 }
5414 d = 0;
5415 ok = 0;
5416 while (ch != EOF && isdigit(ch)) {
5417 d = d*10 + (ch-'0');
5418 ok = 1;
5419 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005420 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005421 ch = i_peek(input);
5422 }
5423 if (ok) return d;
5424
5425//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5426
5427 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005428 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005429}
5430
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005431/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005432 */
5433static int parse_redirect(struct parse_context *ctx,
5434 int fd,
5435 redir_type style,
5436 struct in_str *input)
5437{
5438 struct command *command = ctx->command;
5439 struct redir_struct *redir;
5440 struct redir_struct **redirp;
5441 int dup_num;
5442
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005443 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005444 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005445 /* Check for a '>&1' type redirect */
5446 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5447 if (dup_num == REDIRFD_SYNTAX_ERR)
5448 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005449 } else {
5450 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005451 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005452 if (dup_num) { /* <<-... */
5453 ch = i_getch(input);
5454 nommu_addchr(&ctx->as_string, ch);
5455 ch = i_peek(input);
5456 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005457 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005458
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005459 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005460 int ch = i_peek(input);
5461 if (ch == '|') {
5462 /* >|FILE redirect ("clobbering" >).
5463 * Since we do not support "set -o noclobber" yet,
5464 * >| and > are the same for now. Just eat |.
5465 */
5466 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005467 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005468 }
5469 }
5470
5471 /* Create a new redir_struct and append it to the linked list */
5472 redirp = &command->redirects;
5473 while ((redir = *redirp) != NULL) {
5474 redirp = &(redir->next);
5475 }
5476 *redirp = redir = xzalloc(sizeof(*redir));
5477 /* redir->next = NULL; */
5478 /* redir->rd_filename = NULL; */
5479 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005480 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005481
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005482 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5483 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005484
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005485 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005486 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005487 /* Erik had a check here that the file descriptor in question
5488 * is legit; I postpone that to "run time"
5489 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005490 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5491 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005492 } else {
5493 /* Set ctx->pending_redirect, so we know what to do at the
5494 * end of the next parsed word. */
5495 ctx->pending_redirect = redir;
5496 }
5497 return 0;
5498}
5499
Eric Andersen25f27032001-04-26 23:22:31 +00005500/* If a redirect is immediately preceded by a number, that number is
5501 * supposed to tell which file descriptor to redirect. This routine
5502 * looks for such preceding numbers. In an ideal world this routine
5503 * needs to handle all the following classes of redirects...
5504 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5505 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5506 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5507 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005508 *
5509 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5510 * "2.7 Redirection
5511 * ... If n is quoted, the number shall not be recognized as part of
5512 * the redirection expression. For example:
5513 * echo \2>a
5514 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005515 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005516 *
5517 * A -1 return means no valid number was found,
5518 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005519 */
5520static int redirect_opt_num(o_string *o)
5521{
5522 int num;
5523
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005524 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005525 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005526 num = bb_strtou(o->data, NULL, 10);
5527 if (errno || num < 0)
5528 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005529 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005530 return num;
5531}
5532
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005533#if BB_MMU
5534#define fetch_till_str(as_string, input, word, skip_tabs) \
5535 fetch_till_str(input, word, skip_tabs)
5536#endif
5537static char *fetch_till_str(o_string *as_string,
5538 struct in_str *input,
5539 const char *word,
5540 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005541{
5542 o_string heredoc = NULL_O_STRING;
5543 int past_EOL = 0;
5544 int ch;
5545
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005546 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005547 while (1) {
5548 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005549 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005550 if (ch == '\n') {
5551 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5552 heredoc.data[past_EOL] = '\0';
5553 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5554 return heredoc.data;
5555 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005556 do {
5557 o_addchr(&heredoc, ch);
5558 past_EOL = heredoc.length;
5559 jump_in:
5560 do {
5561 ch = i_getch(input);
5562 nommu_addchr(as_string, ch);
5563 } while (skip_tabs && ch == '\t');
5564 } while (ch == '\n');
5565 }
5566 if (ch == EOF) {
5567 o_free_unsafe(&heredoc);
5568 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005569 }
5570 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005571 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005572 }
5573}
5574
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005575/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5576 * and load them all. There should be exactly heredoc_cnt of them.
5577 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005578static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5579{
5580 struct pipe *pi = ctx->list_head;
5581
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005582 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005583 int i;
5584 struct command *cmd = pi->cmds;
5585
5586 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5587 pi->num_cmds,
5588 cmd->argv ? cmd->argv[0] : "NONE");
5589 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005590 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005591
5592 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5593 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005594 while (redir) {
5595 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005596 char *p;
5597
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005598 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005599 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005600 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005601 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005602 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005603 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005604 return 1;
5605 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005606 free(redir->rd_filename);
5607 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005608 heredoc_cnt--;
5609 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005610 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005611 }
5612 cmd++;
5613 }
5614 pi = pi->next;
5615 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005616#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005617 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005618 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005619 bb_error_msg_and_die("heredoc BUG 2");
5620#endif
5621 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005622}
5623
5624
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005625#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005626static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005627{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005628 pid_t pid;
5629 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005630# if !BB_MMU
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01005631 char **to_free = NULL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005632# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005633
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005634 xpipe(channel);
Pascal Bellard926031b2010-07-04 15:32:38 +02005635 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko05743d72008-02-10 12:10:08 +00005636 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005637 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005638 /* Process substitution is not considered to be usual
5639 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005640 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5641 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005642 bb_signals(0
5643 + (1 << SIGTSTP)
5644 + (1 << SIGTTIN)
5645 + (1 << SIGTTOU)
5646 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005647 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005648 close(channel[0]); /* NB: close _first_, then move fd! */
5649 xmove_fd(channel[1], 1);
5650 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005651 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005652 /* Awful hack for `trap` or $(trap).
5653 *
5654 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5655 * contains an example where "trap" is executed in a subshell:
5656 *
5657 * save_traps=$(trap)
5658 * ...
5659 * eval "$save_traps"
5660 *
5661 * Standard does not say that "trap" in subshell shall print
5662 * parent shell's traps. It only says that its output
5663 * must have suitable form, but then, in the above example
5664 * (which is not supposed to be normative), it implies that.
5665 *
5666 * bash (and probably other shell) does implement it
5667 * (traps are reset to defaults, but "trap" still shows them),
5668 * but as a result, "trap" logic is hopelessly messed up:
5669 *
5670 * # trap
5671 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5672 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5673 * # true | trap <--- trap is in subshell - no output (ditto)
5674 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5675 * trap -- 'echo Ho' SIGWINCH
5676 * # echo `(trap)` <--- in subshell in subshell - output
5677 * trap -- 'echo Ho' SIGWINCH
5678 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5679 * trap -- 'echo Ho' SIGWINCH
5680 *
5681 * The rules when to forget and when to not forget traps
5682 * get really complex and nonsensical.
5683 *
5684 * Our solution: ONLY bare $(trap) or `trap` is special.
5685 */
5686 s = skip_whitespace(s);
5687 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5688 {
5689 static const char *const argv[] = { NULL, NULL };
5690 builtin_trap((char**)argv);
5691 exit(0); /* not _exit() - we need to fflush */
5692 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005693# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005694 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005695 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005696 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005697# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005698 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005699 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5700 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005701 * echo OK
5702 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005703 re_execute_shell(&to_free,
5704 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005705 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005706 G.global_argv + 1,
5707 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005708# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005709 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005710
5711 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005712 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005713# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005714 G.count_SIGCHLD++;
5715//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 +02005716# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005717 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005718# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005719 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005720# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005721 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005722 close_on_exec_on(channel[0]);
5723 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005724}
5725
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005726/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005727static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005728{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005729 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005730 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005731 pid_t pid;
5732 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005733
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005734 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005735
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005736 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005737 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005738 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005739 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005740 if (ch == '\n') {
5741 eol_cnt++;
5742 continue;
5743 }
5744 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005745 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005746 eol_cnt--;
5747 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005748 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005749 }
5750
Denys Vlasenko647553a2009-11-15 19:58:19 +01005751 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005752 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005753 /* We need to extract exitcode. Test case
5754 * "true; echo `sleep 1; false` $?"
5755 * should print 1 */
5756 safe_waitpid(pid, &status, 0);
5757 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5758 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005759}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005760#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005761
Denys Vlasenkoc2704542009-11-20 19:14:19 +01005762#if !ENABLE_HUSH_FUNCTIONS
5763#define parse_group(dest, ctx, input, ch) \
5764 parse_group(ctx, input, ch)
5765#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005766static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005767 struct in_str *input, int ch)
5768{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005769 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005770 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005771 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005772 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005773 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005774 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005775
5776 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005777#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005778 if (ch == '(' && !dest->o_quoted) {
5779 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005780 if (done_word(dest, ctx))
5781 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005782 if (!command->argv)
5783 goto skip; /* (... */
5784 if (command->argv[1]) { /* word word ... (... */
5785 syntax_error_unexpected_ch('(');
5786 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005787 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005788 /* it is "word(..." or "word (..." */
5789 do
5790 ch = i_getch(input);
5791 while (ch == ' ' || ch == '\t');
5792 if (ch != ')') {
5793 syntax_error_unexpected_ch(ch);
5794 return 1;
5795 }
5796 nommu_addchr(&ctx->as_string, ch);
5797 do
5798 ch = i_getch(input);
5799 while (ch == ' ' || ch == '\t' || ch == '\n');
5800 if (ch != '{') {
5801 syntax_error_unexpected_ch(ch);
5802 return 1;
5803 }
5804 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005805 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005806 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005807 }
5808#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005809
5810#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005811 if (command->argv /* word [word]{... */
5812 || dest->length /* word{... */
5813 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005814 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005815 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005816 debug_printf_parse("parse_group return 1: "
5817 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005818 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005819 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005820#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005821
5822#if ENABLE_HUSH_FUNCTIONS
5823 skip:
5824#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005825 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005826 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005827 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005828 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005829 } else {
5830 /* bash does not allow "{echo...", requires whitespace */
5831 ch = i_getch(input);
5832 if (ch != ' ' && ch != '\t' && ch != '\n') {
5833 syntax_error_unexpected_ch(ch);
5834 return 1;
5835 }
5836 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005837 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005838
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005839 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005840#if BB_MMU
5841# define as_string NULL
5842#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005843 char *as_string = NULL;
5844#endif
5845 pipe_list = parse_stream(&as_string, input, endch);
5846#if !BB_MMU
5847 if (as_string)
5848 o_addstr(&ctx->as_string, as_string);
5849#endif
5850 /* empty ()/{} or parse error? */
5851 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005852 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005853 if (!BB_MMU)
5854 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005855 debug_printf_parse("parse_group return 1: "
5856 "parse_stream returned %p\n", pipe_list);
5857 return 1;
5858 }
5859 command->group = pipe_list;
5860#if !BB_MMU
5861 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5862 command->group_as_string = as_string;
5863 debug_printf_parse("end of group, remembering as:'%s'\n",
5864 command->group_as_string);
5865#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005866#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005867 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005868 debug_printf_parse("parse_group return 0\n");
5869 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005870 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005871}
5872
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005873#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005874/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005875static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005876/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005877static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005878{
5879 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005880 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005881 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005882 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005883 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005884 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005885 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005886 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005887 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005888 }
5889}
5890/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005891static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005892{
5893 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005894 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005895 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005896 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005897 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005898 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005899 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005900 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005901 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005902 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005903 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005904 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005905 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005906 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005907 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005908 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005909 continue;
5910 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005911 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005912 }
5913}
5914/* Process `cmd` - copy contents until "`" is seen. Complicated by
5915 * \` quoting.
5916 * "Within the backquoted style of command substitution, backslash
5917 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5918 * The search for the matching backquote shall be satisfied by the first
5919 * backquote found without a preceding backslash; during this search,
5920 * if a non-escaped backquote is encountered within a shell comment,
5921 * a here-document, an embedded command substitution of the $(command)
5922 * form, or a quoted string, undefined results occur. A single-quoted
5923 * or double-quoted string that begins, but does not end, within the
5924 * "`...`" sequence produces undefined results."
5925 * Example Output
5926 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5927 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005928static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005929{
5930 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005931 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005932 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005933 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005934 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005935 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005936 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005937 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005938 if (ch == '\\') {
5939 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005940 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005941 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005942 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005943 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005944 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005945 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005946 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005947 ch = ch2;
5948 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005949 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005950 }
5951}
5952/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5953 * quoting and nested ()s.
5954 * "With the $(command) style of command substitution, all characters
5955 * following the open parenthesis to the matching closing parenthesis
5956 * constitute the command. Any valid shell script can be used for command,
5957 * except a script consisting solely of redirections which produces
5958 * unspecified results."
5959 * Example Output
5960 * echo $(echo '(TEST)' BEST) (TEST) BEST
5961 * echo $(echo 'TEST)' BEST) TEST) BEST
5962 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02005963 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005964 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005965 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005966 * In bash compat mode, it needs to also be able to stop on '}' or ':'
5967 * for ${var:N[:M]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005968 */
Denys Vlasenko74369502010-05-21 19:52:01 +02005969#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005970static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005971{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005972 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02005973 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005974# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005975 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005976# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005977 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
5978
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005979 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005980 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005981 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005982 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005983 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005984 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005985 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005986 if (!dbl)
5987 break;
5988 /* we look for closing )) of $((EXPR)) */
5989 if (i_peek(input) == end_ch) {
5990 i_getch(input); /* eat second ')' */
5991 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00005992 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005993 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005994 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005995 if (ch == '(' || ch == '{') {
5996 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005997 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02005998 o_addchr(dest, ch);
5999 continue;
6000 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006001 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006002 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006003 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006004 continue;
6005 }
6006 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006007 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006008 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006009 continue;
6010 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006011 if (ch == '`') {
6012 add_till_backquote(dest, input);
6013 o_addchr(dest, ch);
6014 continue;
6015 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006016 if (ch == '\\') {
6017 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006018 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006019 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006020 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006021 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006022 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006023 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006024 continue;
6025 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006026 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006027 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006028}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006029#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006030
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006031/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006032#if BB_MMU
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006033#define parse_dollar(as_string, dest, input) \
6034 parse_dollar(dest, input)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006035#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006036#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006037static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006038 o_string *dest,
6039 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00006040{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006041 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006042 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006043
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006044 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006045 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006046 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006047 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00006048 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006049 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006050 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006051 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006052 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006053 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006054 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006055 if (!isalnum(ch) && ch != '_')
6056 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006057 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006058 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006059 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006060 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006061 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006062 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006063 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006064 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006065 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006066 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006067 o_addchr(dest, ch | quote_mask);
6068 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006069 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006070 case '$': /* pid */
6071 case '!': /* last bg pid */
6072 case '?': /* last exit code */
6073 case '#': /* number of args */
6074 case '*': /* args */
6075 case '@': /* args */
6076 goto make_one_char_var;
6077 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04006078 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6079
Denys Vlasenko74369502010-05-21 19:52:01 +02006080 ch = i_getch(input); /* eat '{' */
6081 nommu_addchr(as_string, ch);
6082
6083 ch = i_getch(input); /* first char after '{' */
6084 nommu_addchr(as_string, ch);
6085 /* It should be ${?}, or ${#var},
6086 * or even ${?+subst} - operator acting on a special variable,
6087 * or the beginning of variable name.
6088 */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02006089 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
Denys Vlasenko74369502010-05-21 19:52:01 +02006090 bad_dollar_syntax:
6091 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006092 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02006093 return 1;
6094 }
6095 ch |= quote_mask;
6096
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006097 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02006098 * However, this regresses some of our testsuite cases
6099 * which check invalid constructs like ${%}.
6100 * Oh well... let's check that the var name part is fine... */
6101
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006102 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006103 unsigned pos;
6104
Denys Vlasenko74369502010-05-21 19:52:01 +02006105 o_addchr(dest, ch);
6106 debug_printf_parse(": '%c'\n", ch);
6107
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006108 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006109 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02006110 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00006111 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006112
Denys Vlasenko74369502010-05-21 19:52:01 +02006113 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006114 unsigned end_ch;
6115 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006116 /* handle parameter expansions
6117 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6118 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006119 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6120 goto bad_dollar_syntax;
Denys Vlasenko74369502010-05-21 19:52:01 +02006121 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006122
6123 /* Eat everything until closing '}' (or ':') */
6124 end_ch = '}';
6125 if (ENABLE_HUSH_BASH_COMPAT
6126 && ch == ':'
6127 && !strchr("%#:-=+?"+3, i_peek(input))
6128 ) {
6129 /* It's ${var:N[:M]} thing */
6130 end_ch = '}' * 0x100 + ':';
6131 }
6132 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006133 if (!BB_MMU)
6134 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006135#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006136 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006137#else
6138#error Simple code to only allow ${var} is not implemented
6139#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006140 if (as_string) {
6141 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006142 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006143 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006144
6145 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6146 /* close the first block: */
6147 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6148 /* while parsing N from ${var:N[:M]}... */
6149 if ((end_ch & 0xff) == last_ch) {
6150 /* ...got ':' - parse the rest */
6151 end_ch = '}';
6152 goto again;
6153 }
6154 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6155 o_addstr(dest, "999999999");
6156 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006157 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006158 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006159 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006160 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6161 break;
6162 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006163#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006164 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006165 unsigned pos;
6166
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006167 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006168 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006169# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006170 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006171 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006172 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006173 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6174 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006175 if (!BB_MMU)
6176 pos = dest->length;
6177 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006178 if (as_string) {
6179 o_addstr(as_string, dest->data + pos);
6180 o_addchr(as_string, ')');
6181 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006182 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006183 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006184 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006185 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006186# endif
6187# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006188 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6189 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006190 if (!BB_MMU)
6191 pos = dest->length;
6192 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006193 if (as_string) {
6194 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006195 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006196 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006197 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006198# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006199 break;
6200 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006201#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006202 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006203 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006204 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006205 ch = i_peek(input);
6206 if (isalnum(ch)) { /* it's $_name or $_123 */
6207 ch = '_';
6208 goto make_var;
6209 }
6210 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02006211 /* TODO: $_ and $-: */
6212 /* $_ Shell or shell script name; or last argument of last command
6213 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6214 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006215 /* $- Option flags set by set builtin or shell options (-i etc) */
6216 default:
6217 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00006218 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006219 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00006220 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006221#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00006222}
6223
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006224#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006225#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006226 parse_stream_dquoted(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006227#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006228#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006229static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006230 o_string *dest,
6231 struct in_str *input,
6232 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006233{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006234 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006235 int next;
6236
6237 again:
6238 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006239 if (ch != EOF)
6240 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006241 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006242 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006243 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006244 debug_printf_parse("parse_stream_dquoted return 0\n");
6245 return 0;
6246 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006247 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006248 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006249 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006250 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006251 }
6252 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006253 if (ch != '\n') {
6254 next = i_peek(input);
6255 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006256 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006257 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006258 if (ch == '\\') {
6259 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006260 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006261 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006262 }
6263 /* bash:
6264 * "The backslash retains its special meaning [in "..."]
6265 * only when followed by one of the following characters:
6266 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006267 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006268 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006269 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00006270 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006271 if (ch != '\n') {
6272 o_addqchr(dest, ch);
6273 nommu_addchr(as_string, ch);
6274 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006275 } else {
6276 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00006277 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006278 }
6279 goto again;
6280 }
6281 if (ch == '$') {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006282 if (parse_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006283 debug_printf_parse("parse_stream_dquoted return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006284 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006285 return 1;
6286 }
6287 goto again;
6288 }
6289#if ENABLE_HUSH_TICK
6290 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006291 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006292 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6293 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006294 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006295 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6296 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00006297 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006298 }
6299#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00006300 o_addQchr(dest, ch);
6301 if (ch == '='
6302 && (dest->o_assignment == MAYBE_ASSIGNMENT
6303 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006304 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00006305 ) {
6306 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6307 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006308 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006309#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006310}
6311
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006312/*
6313 * Scan input until EOF or end_trigger char.
6314 * Return a list of pipes to execute, or NULL on EOF
6315 * or if end_trigger character is met.
6316 * On syntax error, exit is shell is not interactive,
6317 * reset parsing machinery and start parsing anew,
6318 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006319 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006320static struct pipe *parse_stream(char **pstring,
6321 struct in_str *input,
6322 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006323{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006324 struct parse_context ctx;
6325 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006326 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006327 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006328
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006329 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006330 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006331 * found. When recursing, quote state is passed in via dest->o_escape.
6332 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006333 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006334 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006335 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006336
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006337 /* If very first arg is "" or '', dest.data may end up NULL.
6338 * Preventing this: */
6339 o_addchr(&dest, '\0');
6340 dest.length = 0;
6341
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006342 G.ifs = get_local_var_value("IFS");
6343 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01006344 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006345
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006346 reset:
6347#if ENABLE_HUSH_INTERACTIVE
6348 input->promptmode = 0; /* PS1 */
6349#endif
6350 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6351 initialize_context(&ctx);
6352 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006353 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006354 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006355 const char *is_ifs;
6356 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006357 int ch;
6358 int next;
6359 int redir_fd;
6360 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006361
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006362 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006363 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006364 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006365 goto parse_error;
6366 }
6367 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006368 is_in_dquote = 0;
6369 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006370 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006371 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6372 ch, ch, dest.o_escape);
6373 if (ch == EOF) {
6374 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006375
6376 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006377 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006378 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006379 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006380 /* end_trigger == '}' case errors out earlier,
6381 * checking only ')' */
6382 if (end_trigger == ')') {
6383 syntax_error_unterm_ch('('); /* exits */
6384 /* goto parse_error; */
6385 }
6386
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006387 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006388 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006389 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006390 o_free(&dest);
6391 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006392 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006393 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006394 /* (this makes bare "&" cmd a no-op.
6395 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006396 if (pi->num_cmds == 0
6397 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6398 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006399 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006400 pi = NULL;
6401 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006402#if !BB_MMU
6403 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6404 if (pstring)
6405 *pstring = ctx.as_string.data;
6406 else
6407 o_free_unsafe(&ctx.as_string);
6408#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006409 debug_leave();
6410 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006411 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006412 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006413 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006414
6415 next = '\0';
6416 if (ch != '\n')
6417 next = i_peek(input);
6418
6419 is_special = "{}<>;&|()#'" /* special outside of "str" */
6420 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6421 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02006422 if (ctx.command->argv /* word [word]{... - non-special */
6423 || dest.length /* word{... - non-special */
6424 || dest.o_quoted /* ""{... - non-special */
6425 || (next != ';' /* }; - special */
6426 && next != ')' /* }) - special */
6427 && next != '&' /* }& and }&& ... - special */
6428 && next != '|' /* }|| ... - special */
6429 && !strchr(G.ifs, next) /* {word - non-special */
6430 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006431 ) {
6432 /* They are not special, skip "{}" */
6433 is_special += 2;
6434 }
6435 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006436 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006437
6438 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006439 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006440 o_addQchr(&dest, ch);
6441 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6442 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006443 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006444 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006445 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006446 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006447 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006448 continue;
6449 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006450
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006451 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006452 if (done_word(&dest, &ctx)) {
6453 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006454 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006455 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006456#if ENABLE_HUSH_CASE
6457 /* "case ... in <newline> word) ..." -
6458 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006459 if (ctx.command->argv == NULL
6460 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006461 ) {
6462 continue;
6463 }
6464#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006465 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006466 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006467 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6468 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006469 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006470 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006471 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006472 heredoc_cnt = 0;
6473 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006474 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006475 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006476 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006477 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006478 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006479 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006480
6481 /* "cmd}" or "cmd }..." without semicolon or &:
6482 * } is an ordinary char in this case, even inside { cmd; }
6483 * Pathological example: { ""}; } should exec "}" cmd
6484 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006485 if (ch == '}') {
6486 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6487 || dest.length != 0 /* word} */
6488 || dest.o_quoted /* ""} */
6489 ) {
6490 goto ordinary_char;
6491 }
6492 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6493 goto skip_end_trigger;
6494 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006495 }
6496
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006497 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006498 && (ch != ';' || heredoc_cnt == 0)
6499#if ENABLE_HUSH_CASE
6500 && (ch != ')'
6501 || ctx.ctx_res_w != RES_MATCH
6502 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6503 )
6504#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006505 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006506 if (heredoc_cnt) {
6507 /* This is technically valid:
6508 * { cat <<HERE; }; echo Ok
6509 * heredoc
6510 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006511 * HERE
6512 * but we don't support this.
6513 * We require heredoc to be in enclosing {}/(),
6514 * if any.
6515 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006516 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006517 goto parse_error;
6518 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006519 if (done_word(&dest, &ctx)) {
6520 goto parse_error;
6521 }
6522 done_pipe(&ctx, PIPE_SEQ);
6523 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006524 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006525 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006526 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006527 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006528 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006529#if !BB_MMU
6530 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6531 if (pstring)
6532 *pstring = ctx.as_string.data;
6533 else
6534 o_free_unsafe(&ctx.as_string);
6535#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006536 debug_leave();
6537 debug_printf_parse("parse_stream return %p: "
6538 "end_trigger char found\n",
6539 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006540 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006541 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006542 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006543 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006544 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006545 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006546
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006547 /* Catch <, > before deciding whether this word is
6548 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6549 switch (ch) {
6550 case '>':
6551 redir_fd = redirect_opt_num(&dest);
6552 if (done_word(&dest, &ctx)) {
6553 goto parse_error;
6554 }
6555 redir_style = REDIRECT_OVERWRITE;
6556 if (next == '>') {
6557 redir_style = REDIRECT_APPEND;
6558 ch = i_getch(input);
6559 nommu_addchr(&ctx.as_string, ch);
6560 }
6561#if 0
6562 else if (next == '(') {
6563 syntax_error(">(process) not supported");
6564 goto parse_error;
6565 }
6566#endif
6567 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6568 goto parse_error;
6569 continue; /* back to top of while (1) */
6570 case '<':
6571 redir_fd = redirect_opt_num(&dest);
6572 if (done_word(&dest, &ctx)) {
6573 goto parse_error;
6574 }
6575 redir_style = REDIRECT_INPUT;
6576 if (next == '<') {
6577 redir_style = REDIRECT_HEREDOC;
6578 heredoc_cnt++;
6579 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6580 ch = i_getch(input);
6581 nommu_addchr(&ctx.as_string, ch);
6582 } else if (next == '>') {
6583 redir_style = REDIRECT_IO;
6584 ch = i_getch(input);
6585 nommu_addchr(&ctx.as_string, ch);
6586 }
6587#if 0
6588 else if (next == '(') {
6589 syntax_error("<(process) not supported");
6590 goto parse_error;
6591 }
6592#endif
6593 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6594 goto parse_error;
6595 continue; /* back to top of while (1) */
6596 }
6597
6598 if (dest.o_assignment == MAYBE_ASSIGNMENT
6599 /* check that we are not in word in "a=1 2>word b=1": */
6600 && !ctx.pending_redirect
6601 ) {
6602 /* ch is a special char and thus this word
6603 * cannot be an assignment */
6604 dest.o_assignment = NOT_ASSIGNMENT;
6605 }
6606
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006607 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6608
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006609 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006610 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006611 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006612 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006613 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006614 if (ch == EOF || ch == '\n')
6615 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006616 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006617 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006618 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006619 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006620 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006621 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006622 }
6623 break;
6624 case '\\':
6625 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006626 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006627 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006628 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006629 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006630 if (ch != '\n') {
6631 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006632 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006633 o_addchr(&dest, ch);
6634 nommu_addchr(&ctx.as_string, ch);
6635 /* Example: echo Hello \2>file
6636 * we need to know that word 2 is quoted */
6637 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006638 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006639#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006640 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006641 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6642 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006643 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006644#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006645 break;
6646 case '$':
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006647 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006648 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006649 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006650 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006651 }
Eric Andersen25f27032001-04-26 23:22:31 +00006652 break;
6653 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006654 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006655 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006656 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006657 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006658 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006659 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006660 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006661 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006662 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006663 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006664 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006665 }
Eric Andersen25f27032001-04-26 23:22:31 +00006666 break;
6667 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006668 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006669 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006670 if (dest.o_assignment == NOT_ASSIGNMENT)
6671 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006672 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006673#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006674 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006675 unsigned pos;
6676
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006677 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6678 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006679 pos = dest.length;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006680 add_till_backquote(&dest, input);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006681# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006682 o_addstr(&ctx.as_string, dest.data + pos);
6683 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006684# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006685 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6686 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006687 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006688 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006689#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006690 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006691#if ENABLE_HUSH_CASE
6692 case_semi:
6693#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006694 if (done_word(&dest, &ctx)) {
6695 goto parse_error;
6696 }
6697 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006698#if ENABLE_HUSH_CASE
6699 /* Eat multiple semicolons, detect
6700 * whether it means something special */
6701 while (1) {
6702 ch = i_peek(input);
6703 if (ch != ';')
6704 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006705 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006706 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006707 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006708 ctx.ctx_dsemicolon = 1;
6709 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006710 break;
6711 }
6712 }
6713#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006714 new_cmd:
6715 /* We just finished a cmd. New one may start
6716 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006717 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006718 break;
6719 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006720 if (done_word(&dest, &ctx)) {
6721 goto parse_error;
6722 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006723 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006724 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006725 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006726 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006727 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006728 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006729 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006730 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006731 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006732 if (done_word(&dest, &ctx)) {
6733 goto parse_error;
6734 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006735#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006736 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006737 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006738#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006739 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006740 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006741 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006742 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006743 } else {
6744 /* we could pick up a file descriptor choice here
6745 * with redirect_opt_num(), but bash doesn't do it.
6746 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006747 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006748#if !BB_MMU
6749 o_reset_to_empty_unquoted(&ctx.as_string);
6750#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006751 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006752 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006753 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006754#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006755 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006756 if (ctx.ctx_res_w == RES_MATCH
6757 && ctx.command->argv == NULL /* not (word|(... */
6758 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006759 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006760 ) {
6761 continue;
6762 }
6763#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006764 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006765 if (parse_group(&dest, &ctx, input, ch) != 0) {
6766 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006767 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006768 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006769 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006770#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006771 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006772 goto case_semi;
6773#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006774 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006775 /* proper use of this character is caught by end_trigger:
6776 * if we see {, we call parse_group(..., end_trigger='}')
6777 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006778 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006779 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006780 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006781 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006782 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006783 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006784 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006785
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006786 parse_error:
6787 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006788 struct parse_context *pctx;
6789 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006790
6791 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006792 * Sample for finding leaks on syntax error recovery path.
6793 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006794 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006795 * Samples to catch leaks at execution:
6796 * while if (true | {true;}); then echo ok; fi; do break; done
6797 * 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 +00006798 */
6799 pctx = &ctx;
6800 do {
6801 /* Update pipe/command counts,
6802 * otherwise freeing may miss some */
6803 done_pipe(pctx, PIPE_SEQ);
6804 debug_printf_clean("freeing list %p from ctx %p\n",
6805 pctx->list_head, pctx);
6806 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006807 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006808 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006809#if !BB_MMU
6810 o_free_unsafe(&pctx->as_string);
6811#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006812 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006813 if (pctx != &ctx) {
6814 free(pctx);
6815 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006816 IF_HAS_KEYWORDS(pctx = p2;)
6817 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006818 /* Free text, clear all dest fields */
6819 o_free(&dest);
6820 /* If we are not in top-level parse, we return,
6821 * our caller will propagate error.
6822 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006823 if (end_trigger != ';') {
6824#if !BB_MMU
6825 if (pstring)
6826 *pstring = NULL;
6827#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006828 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006829 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006830 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006831 /* Discard cached input, force prompt */
6832 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006833 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006834 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006835 }
Eric Andersen25f27032001-04-26 23:22:31 +00006836}
6837
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006838/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006839 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6840 * end_trigger controls how often we stop parsing
6841 * NUL: parse all, execute, return
6842 * ';': parse till ';' or newline, execute, repeat till EOF
6843 */
6844static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006845{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006846 /* Why we need empty flag?
6847 * An obscure corner case "false; ``; echo $?":
6848 * empty command in `` should still set $? to 0.
6849 * But we can't just set $? to 0 at the start,
6850 * this breaks "false; echo `echo $?`" case.
6851 */
6852 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006853 while (1) {
6854 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006855
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006856 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006857 if (!pipe_list) { /* EOF */
6858 if (empty)
6859 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006860 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006861 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006862 debug_print_tree(pipe_list, 0);
6863 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6864 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006865 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006866 }
Eric Andersen25f27032001-04-26 23:22:31 +00006867}
6868
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006869static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006870{
6871 struct in_str input;
6872 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006873 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006874}
6875
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006876static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006877{
Eric Andersen25f27032001-04-26 23:22:31 +00006878 struct in_str input;
6879 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006880 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006881}
6882
Denis Vlasenkof9375282009-04-05 19:13:39 +00006883/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006884static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006885{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006886 unsigned sig;
6887 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006888 sigset_t old_blocked_set;
6889
6890 if (!G.inherited_set_is_saved) {
6891 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6892 G.inherited_set = G.blocked_set;
6893 }
6894 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006895
Denis Vlasenkof9375282009-04-05 19:13:39 +00006896 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006897 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006898 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006899 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006900 mask |= SPECIAL_JOB_SIGS;
6901 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006902 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006903
Denis Vlasenkof9375282009-04-05 19:13:39 +00006904 sig = 0;
6905 while (mask) {
6906 if (mask & 1)
6907 sigaddset(&G.blocked_set, sig);
6908 mask >>= 1;
6909 sig++;
6910 }
6911 sigdelset(&G.blocked_set, SIGCHLD);
6912
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006913 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
6914 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6915
Denis Vlasenkof9375282009-04-05 19:13:39 +00006916 /* POSIX allows shell to re-enable SIGCHLD
6917 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006918#if ENABLE_HUSH_FAST
6919 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006920 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006921 signal(SIGCHLD, SIGCHLD_handler);
6922#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006923 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006924 signal(SIGCHLD, SIG_DFL);
6925#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006926
6927 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00006928}
6929
6930#if ENABLE_HUSH_JOB
6931/* helper */
6932static void maybe_set_to_sigexit(int sig)
6933{
6934 void (*handler)(int);
6935 /* non_DFL_mask'ed signals are, well, masked,
6936 * no need to set handler for them.
6937 */
6938 if (!((G.non_DFL_mask >> sig) & 1)) {
6939 handler = signal(sig, sigexit);
6940 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6941 signal(sig, handler);
6942 }
6943}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006944/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006945static void set_fatal_handlers(void)
6946{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006947 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006948 if (HUSH_DEBUG) {
6949 maybe_set_to_sigexit(SIGILL );
6950 maybe_set_to_sigexit(SIGFPE );
6951 maybe_set_to_sigexit(SIGBUS );
6952 maybe_set_to_sigexit(SIGSEGV);
6953 maybe_set_to_sigexit(SIGTRAP);
6954 } /* else: hush is perfect. what SEGV? */
6955 maybe_set_to_sigexit(SIGABRT);
6956 /* bash 3.2 seems to handle these just like 'fatal' ones */
6957 maybe_set_to_sigexit(SIGPIPE);
6958 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006959 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006960 * if we aren't interactive... but in this case
6961 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006962 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006963 /*maybe_set_to_sigexit(SIGTERM);*/
6964 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006965}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006966#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006967
Denis Vlasenkod5762932009-03-31 11:22:57 +00006968static int set_mode(const char cstate, const char mode)
6969{
6970 int state = (cstate == '-' ? 1 : 0);
6971 switch (mode) {
6972 case 'n': G.fake_mode = state; break;
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02006973 case 'x': G.x_mode = state; break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00006974 default: return EXIT_FAILURE;
6975 }
6976 return EXIT_SUCCESS;
6977}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006978
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006979int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006980int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006981{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006982 static const struct variable const_shell_ver = {
6983 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006984 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006985 .max_len = 1, /* 0 can provoke free(name) */
6986 .flg_export = 1,
6987 .flg_read_only = 1,
6988 };
Eric Andersen25f27032001-04-26 23:22:31 +00006989 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006990 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006991 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006992 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006993
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006994 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02006995 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006996 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006997#if !BB_MMU
6998 G.argv0_for_re_execing = argv[0];
6999#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007000 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007001 G.shell_ver = const_shell_ver; /* copying struct here */
7002 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007003 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007004 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7005 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007006 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007007 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007008 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007009 if (e) while (*e) {
7010 char *value = strchr(*e, '=');
7011 if (value) { /* paranoia */
7012 cur_var->next = xzalloc(sizeof(*cur_var));
7013 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007014 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007015 cur_var->max_len = strlen(*e);
7016 cur_var->flg_export = 1;
7017 }
7018 e++;
7019 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007020 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007021 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007022 putenv((char *)hush_version_str);
7023
7024 /* Export PWD */
7025 set_pwd_var(/*exp:*/ 1);
7026 /* bash also exports SHLVL and _,
7027 * and sets (but doesn't export) the following variables:
7028 * BASH=/bin/bash
7029 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7030 * BASH_VERSION='3.2.0(1)-release'
7031 * HOSTTYPE=i386
7032 * MACHTYPE=i386-pc-linux-gnu
7033 * OSTYPE=linux-gnu
7034 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007035 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007036 * EUID=<NNNNN>
7037 * UID=<NNNNN>
7038 * GROUPS=()
7039 * LINES=<NNN>
7040 * COLUMNS=<NNN>
7041 * BASH_ARGC=()
7042 * BASH_ARGV=()
7043 * BASH_LINENO=()
7044 * BASH_SOURCE=()
7045 * DIRSTACK=()
7046 * PIPESTATUS=([0]="0")
7047 * HISTFILE=/<xxx>/.bash_history
7048 * HISTFILESIZE=500
7049 * HISTSIZE=500
7050 * MAILCHECK=60
7051 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7052 * SHELL=/bin/bash
7053 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7054 * TERM=dumb
7055 * OPTERR=1
7056 * OPTIND=1
7057 * IFS=$' \t\n'
7058 * PS1='\s-\v\$ '
7059 * PS2='> '
7060 * PS4='+ '
7061 */
7062
Denis Vlasenko38f63192007-01-22 09:03:07 +00007063#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007064 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007065#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007066 G.global_argc = argc;
7067 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007068 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007069 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007070
Denis Vlasenkoed782372009-04-10 00:45:02 +00007071 if (setjmp(die_jmp)) {
7072 /* xfunc has failed! die die die */
7073 /* no EXIT traps, this is an escape hatch! */
7074 G.exiting = 1;
7075 hush_exit(xfunc_error_retval);
7076 }
7077
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007078 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007079 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007080 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007081 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007082 * in order to intercept (more) signals.
7083 */
7084
7085 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007086 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007087 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007088 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007089 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007090#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007091 "<:$:R:V:"
7092# if ENABLE_HUSH_FUNCTIONS
7093 "F:"
7094# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007095#endif
7096 );
7097 if (opt <= 0)
7098 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007099 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007100 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007101 /* Possibilities:
7102 * sh ... -c 'script'
7103 * sh ... -c 'script' ARG0 [ARG1...]
7104 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007105 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007106 * "" needs to be replaced with NULL
7107 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007108 * Note: the form without ARG0 never happens:
7109 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007110 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007111 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007112 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007113 G.root_ppid = getppid();
7114 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007115 G.global_argv = argv + optind;
7116 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007117 if (builtin_argc) {
7118 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7119 const struct built_in_command *x;
7120
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007121 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007122 x = find_builtin(optarg);
7123 if (x) { /* paranoia */
7124 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7125 G.global_argv += builtin_argc;
7126 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007127 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007128 }
7129 goto final_return;
7130 }
7131 if (!G.global_argv[0]) {
7132 /* -c 'script' (no params): prevent empty $0 */
7133 G.global_argv--; /* points to argv[i] of 'script' */
7134 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007135 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007136 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007137 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007138 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007139 goto final_return;
7140 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007141 /* Well, we cannot just declare interactiveness,
7142 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007143 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007144 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007145 case 's':
7146 /* "-s" means "read from stdin", but this is how we always
7147 * operate, so simply do nothing here. */
7148 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007149#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007150 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007151 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007152 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007153 case '$': {
7154 unsigned long long empty_trap_mask;
7155
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007156 G.root_pid = bb_strtou(optarg, &optarg, 16);
7157 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007158 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7159 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007160 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7161 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007162 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007163 optarg++;
7164 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007165 optarg++;
7166 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7167 if (empty_trap_mask != 0) {
7168 int sig;
7169 init_sigmasks();
7170 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7171 for (sig = 1; sig < NSIG; sig++) {
7172 if (empty_trap_mask & (1LL << sig)) {
7173 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7174 sigaddset(&G.blocked_set, sig);
7175 }
7176 }
7177 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7178 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007179# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007180 optarg++;
7181 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007182# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007183 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007184 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007185 case 'R':
7186 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007187 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007188 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007189# if ENABLE_HUSH_FUNCTIONS
7190 case 'F': {
7191 struct function *funcp = new_function(optarg);
7192 /* funcp->name is already set to optarg */
7193 /* funcp->body is set to NULL. It's a special case. */
7194 funcp->body_as_string = argv[optind];
7195 optind++;
7196 break;
7197 }
7198# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007199#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007200 case 'n':
7201 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007202 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007203 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007204 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007205#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007206 fprintf(stderr, "Usage: sh [FILE]...\n"
7207 " or: sh -c command [args]...\n\n");
7208 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007209#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007210 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007211#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007212 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007213 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007214
Denys Vlasenkodea47882009-10-09 15:40:49 +02007215 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007216 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007217 G.root_ppid = getppid();
7218 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007219
7220 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007221 if (argv[0] && argv[0][0] == '-') {
7222 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007223 debug_printf("sourcing /etc/profile\n");
7224 input = fopen_for_read("/etc/profile");
7225 if (input != NULL) {
7226 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007227 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007228 parse_and_run_file(input);
7229 fclose(input);
7230 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007231 /* bash: after sourcing /etc/profile,
7232 * tries to source (in the given order):
7233 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007234 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007235 * bash also sources ~/.bash_logout on exit.
7236 * If called as sh, skips .bash_XXX files.
7237 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007238 }
7239
Denis Vlasenkof9375282009-04-05 19:13:39 +00007240 if (argv[optind]) {
7241 FILE *input;
7242 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007243 * "bash <script>" (which is never interactive (unless -i?))
7244 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007245 * If called as sh, does the same but with $ENV.
7246 */
7247 debug_printf("running script '%s'\n", argv[optind]);
7248 G.global_argv = argv + optind;
7249 G.global_argc = argc - optind;
7250 input = xfopen_for_read(argv[optind]);
7251 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007252 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007253 parse_and_run_file(input);
7254#if ENABLE_FEATURE_CLEAN_UP
7255 fclose(input);
7256#endif
7257 goto final_return;
7258 }
7259
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007260 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007261 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007262 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007263
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007264 /* A shell is interactive if the '-i' flag was given,
7265 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007266 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007267 * no arguments remaining or the -s flag given
7268 * standard input is a terminal
7269 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007270 * Refer to Posix.2, the description of the 'sh' utility.
7271 */
7272#if ENABLE_HUSH_JOB
7273 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007274 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7275 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7276 if (G_saved_tty_pgrp < 0)
7277 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007278
7279 /* try to dup stdin to high fd#, >= 255 */
7280 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7281 if (G_interactive_fd < 0) {
7282 /* try to dup to any fd */
7283 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007284 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007285 /* give up */
7286 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007287 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007288 }
7289 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007290// TODO: track & disallow any attempts of user
7291// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007292 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007293 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007294 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007295 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007296
Mike Frysinger38478a62009-05-20 04:48:06 -04007297 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007298 /* If we were run as 'hush &', sleep until we are
7299 * in the foreground (tty pgrp == our pgrp).
7300 * If we get started under a job aware app (like bash),
7301 * make sure we are now in charge so we don't fight over
7302 * who gets the foreground */
7303 while (1) {
7304 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007305 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7306 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007307 break;
7308 /* send TTIN to ourself (should stop us) */
7309 kill(- shell_pgrp, SIGTTIN);
7310 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007311 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007312
Denis Vlasenkof9375282009-04-05 19:13:39 +00007313 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007314 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007315
Mike Frysinger38478a62009-05-20 04:48:06 -04007316 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007317 /* Set other signals to restore saved_tty_pgrp */
7318 set_fatal_handlers();
7319 /* Put ourselves in our own process group
7320 * (bash, too, does this only if ctty is available) */
7321 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7322 /* Grab control of the terminal */
7323 tcsetpgrp(G_interactive_fd, getpid());
7324 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007325 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007326 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007327 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007328 } else {
7329 init_sigmasks();
7330 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007331#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007332 /* No job control compiled in, only prompt/line editing */
7333 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007334 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7335 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007336 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007337 G_interactive_fd = dup(STDIN_FILENO);
7338 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007339 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007340 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007341 }
7342 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007343 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007344 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007345 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007346 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007347#else
7348 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007349 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007350#endif
7351 /* bash:
7352 * if interactive but not a login shell, sources ~/.bashrc
7353 * (--norc turns this off, --rcfile <file> overrides)
7354 */
7355
7356 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007357 /* note: ash and hush share this string */
7358 printf("\n\n%s %s\n"
7359 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7360 "\n",
7361 bb_banner,
7362 "hush - the humble shell"
7363 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007364 }
7365
Denis Vlasenkof9375282009-04-05 19:13:39 +00007366 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007367
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007368 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007369#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007370 if (G.cwd != bb_msg_unknown)
7371 free((char*)G.cwd);
7372 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007373 while (cur_var) {
7374 struct variable *tmp = cur_var;
7375 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007376 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007377 cur_var = cur_var->next;
7378 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007379 }
Eric Andersen25f27032001-04-26 23:22:31 +00007380#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007381 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007382}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007383
7384
7385#if ENABLE_LASH
7386int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7387int lash_main(int argc, char **argv)
7388{
Denys Vlasenko07934912009-08-20 03:40:04 +02007389 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007390 return hush_main(argc, argv);
7391}
7392#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007393
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007394#if ENABLE_MSH
7395int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7396int msh_main(int argc, char **argv)
7397{
7398 //bb_error_msg("msh is deprecated, please use hush instead");
7399 return hush_main(argc, argv);
7400}
7401#endif
7402
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007403
7404/*
7405 * Built-ins
7406 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007407static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007408{
7409 return 0;
7410}
7411
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007412static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007413{
7414 int argc = 0;
7415 while (*argv) {
7416 argc++;
7417 argv++;
7418 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007419 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007420}
7421
7422static int FAST_FUNC builtin_test(char **argv)
7423{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007424 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007425}
7426
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007427static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007428{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007429 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007430}
7431
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007432#if ENABLE_PRINTF
7433static int FAST_FUNC builtin_printf(char **argv)
7434{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007435 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007436}
7437#endif
7438
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007439static char **skip_dash_dash(char **argv)
7440{
7441 argv++;
7442 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7443 argv++;
7444 return argv;
7445}
7446
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007447static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007448{
7449 int rcode = EXIT_SUCCESS;
7450
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007451 argv = skip_dash_dash(argv);
7452 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007453 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007454 /* bash:
7455 * eval "echo Hi; done" ("done" is syntax error):
7456 * "echo Hi" will not execute too.
7457 */
7458 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007459 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007460 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007461 }
7462 return rcode;
7463}
7464
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007465static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007466{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007467 const char *newdir;
7468
7469 argv = skip_dash_dash(argv);
7470 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007471 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007472 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007473 * bash says "bash: cd: HOME not set" and does nothing
7474 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007475 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007476 const char *home = get_local_var_value("HOME");
7477 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007478 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007479 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007480 /* Mimic bash message exactly */
7481 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007482 return EXIT_FAILURE;
7483 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007484 /* Read current dir (get_cwd(1) is inside) and set PWD.
7485 * Note: do not enforce exporting. If PWD was unset or unexported,
7486 * set it again, but do not export. bash does the same.
7487 */
7488 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007489 return EXIT_SUCCESS;
7490}
7491
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007492static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007493{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007494 argv = skip_dash_dash(argv);
7495 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007496 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007497
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007498 /* Careful: we can end up here after [v]fork. Do not restore
7499 * tty pgrp then, only top-level shell process does that */
7500 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7501 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7502
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007503 /* TODO: if exec fails, bash does NOT exit! We do.
7504 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7505 * and tcsetpgrp, and this is inherently racy.
7506 */
7507 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007508}
7509
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007510static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007511{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007512 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007513
7514 /* interactive bash:
7515 * # trap "echo EEE" EXIT
7516 * # exit
7517 * exit
7518 * There are stopped jobs.
7519 * (if there are _stopped_ jobs, running ones don't count)
7520 * # exit
7521 * exit
7522 # EEE (then bash exits)
7523 *
7524 * we can use G.exiting = -1 as indicator "last cmd was exit"
7525 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007526
7527 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007528 argv = skip_dash_dash(argv);
7529 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007530 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007531 /* mimic bash: exit 123abc == exit 255 + error msg */
7532 xfunc_error_retval = 255;
7533 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007534 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007535}
7536
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007537static void print_escaped(const char *s)
7538{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007539 if (*s == '\'')
7540 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007541 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007542 const char *p = strchrnul(s, '\'');
7543 /* print 'xxxx', possibly just '' */
7544 printf("'%.*s'", (int)(p - s), s);
7545 if (*p == '\0')
7546 break;
7547 s = p;
7548 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007549 /* s points to '; print "'''...'''" */
7550 putchar('"');
7551 do putchar('\''); while (*++s == '\'');
7552 putchar('"');
7553 } while (*s);
7554}
7555
Denys Vlasenko295fef82009-06-03 12:47:26 +02007556#if !ENABLE_HUSH_LOCAL
7557#define helper_export_local(argv, exp, lvl) \
7558 helper_export_local(argv, exp)
7559#endif
7560static void helper_export_local(char **argv, int exp, int lvl)
7561{
7562 do {
7563 char *name = *argv;
7564
7565 /* So far we do not check that name is valid (TODO?) */
7566
7567 if (strchr(name, '=') == NULL) {
7568 struct variable *var;
7569
7570 var = get_local_var(name);
7571 if (exp == -1) { /* unexporting? */
7572 /* export -n NAME (without =VALUE) */
7573 if (var) {
7574 var->flg_export = 0;
7575 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7576 unsetenv(name);
7577 } /* else: export -n NOT_EXISTING_VAR: no-op */
7578 continue;
7579 }
7580 if (exp == 1) { /* exporting? */
7581 /* export NAME (without =VALUE) */
7582 if (var) {
7583 var->flg_export = 1;
7584 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7585 putenv(var->varstr);
7586 continue;
7587 }
7588 }
7589 /* Exporting non-existing variable.
7590 * bash does not put it in environment,
7591 * but remembers that it is exported,
7592 * and does put it in env when it is set later.
7593 * We just set it to "" and export. */
7594 /* Or, it's "local NAME" (without =VALUE).
7595 * bash sets the value to "". */
7596 name = xasprintf("%s=", name);
7597 } else {
7598 /* (Un)exporting/making local NAME=VALUE */
7599 name = xstrdup(name);
7600 }
7601 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7602 } while (*++argv);
7603}
7604
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007605static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007606{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007607 unsigned opt_unexport;
7608
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007609#if ENABLE_HUSH_EXPORT_N
7610 /* "!": do not abort on errors */
7611 opt_unexport = getopt32(argv, "!n");
7612 if (opt_unexport == (uint32_t)-1)
7613 return EXIT_FAILURE;
7614 argv += optind;
7615#else
7616 opt_unexport = 0;
7617 argv++;
7618#endif
7619
7620 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007621 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007622 if (e) {
7623 while (*e) {
7624#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007625 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007626#else
7627 /* ash emits: export VAR='VAL'
7628 * bash: declare -x VAR="VAL"
7629 * we follow ash example */
7630 const char *s = *e++;
7631 const char *p = strchr(s, '=');
7632
7633 if (!p) /* wtf? take next variable */
7634 continue;
7635 /* export var= */
7636 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007637 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007638 putchar('\n');
7639#endif
7640 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007641 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007642 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007643 return EXIT_SUCCESS;
7644 }
7645
Denys Vlasenko295fef82009-06-03 12:47:26 +02007646 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007647
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007648 return EXIT_SUCCESS;
7649}
7650
Denys Vlasenko295fef82009-06-03 12:47:26 +02007651#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007652static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007653{
7654 if (G.func_nest_level == 0) {
7655 bb_error_msg("%s: not in a function", argv[0]);
7656 return EXIT_FAILURE; /* bash compat */
7657 }
7658 helper_export_local(argv, 0, G.func_nest_level);
7659 return EXIT_SUCCESS;
7660}
7661#endif
7662
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007663static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007664{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007665 int sig;
7666 char *new_cmd;
7667
7668 if (!G.traps)
7669 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7670
7671 argv++;
7672 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007673 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007674 /* No args: print all trapped */
7675 for (i = 0; i < NSIG; ++i) {
7676 if (G.traps[i]) {
7677 printf("trap -- ");
7678 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007679 /* note: bash adds "SIG", but only if invoked
7680 * as "bash". If called as "sh", or if set -o posix,
7681 * then it prints short signal names.
7682 * We are printing short names: */
7683 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007684 }
7685 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007686 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007687 return EXIT_SUCCESS;
7688 }
7689
7690 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007691 /* If first arg is a number: reset all specified signals */
7692 sig = bb_strtou(*argv, NULL, 10);
7693 if (errno == 0) {
7694 int ret;
7695 process_sig_list:
7696 ret = EXIT_SUCCESS;
7697 while (*argv) {
7698 sig = get_signum(*argv++);
7699 if (sig < 0 || sig >= NSIG) {
7700 ret = EXIT_FAILURE;
7701 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007702 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007703 continue;
7704 }
7705
7706 free(G.traps[sig]);
7707 G.traps[sig] = xstrdup(new_cmd);
7708
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007709 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007710 get_signame(sig), sig, G.traps[sig]);
7711
7712 /* There is no signal for 0 (EXIT) */
7713 if (sig == 0)
7714 continue;
7715
7716 if (new_cmd) {
7717 sigaddset(&G.blocked_set, sig);
7718 } else {
7719 /* There was a trap handler, we are removing it
7720 * (if sig has non-DFL handling,
7721 * we don't need to do anything) */
7722 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7723 continue;
7724 sigdelset(&G.blocked_set, sig);
7725 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007726 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007727 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007728 return ret;
7729 }
7730
7731 if (!argv[1]) { /* no second arg */
7732 bb_error_msg("trap: invalid arguments");
7733 return EXIT_FAILURE;
7734 }
7735
7736 /* First arg is "-": reset all specified to default */
7737 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7738 /* Everything else: set arg as signal handler
7739 * (includes "" case, which ignores signal) */
7740 if (argv[0][0] == '-') {
7741 if (argv[0][1] == '\0') { /* "-" */
7742 /* new_cmd remains NULL: "reset these sigs" */
7743 goto reset_traps;
7744 }
7745 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7746 argv++;
7747 }
7748 /* else: "-something", no special meaning */
7749 }
7750 new_cmd = *argv;
7751 reset_traps:
7752 argv++;
7753 goto process_sig_list;
7754}
7755
Mike Frysinger93cadc22009-05-27 17:06:25 -04007756/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007757static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007758{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007759 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007760
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007761 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007762 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007763 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007764
7765 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007766 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007767 type = "an alias";*/
7768#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007769 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007770 type = "a function";
7771#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007772 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007773 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007774 else if ((path = find_in_path(*argv)) != NULL)
7775 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007776 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007777 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007778 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007779 continue;
7780 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007781
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007782 printf("%s is %s\n", *argv, type);
7783 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007784 }
7785
7786 return ret;
7787}
7788
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007789#if ENABLE_HUSH_JOB
7790/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007791static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007792{
7793 int i, jobnum;
7794 struct pipe *pi;
7795
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007796 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007797 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007798
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007799 /* If they gave us no args, assume they want the last backgrounded task */
7800 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007801 for (pi = G.job_list; pi; pi = pi->next) {
7802 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007803 goto found;
7804 }
7805 }
7806 bb_error_msg("%s: no current job", argv[0]);
7807 return EXIT_FAILURE;
7808 }
7809 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7810 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7811 return EXIT_FAILURE;
7812 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007813 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007814 if (pi->jobid == jobnum) {
7815 goto found;
7816 }
7817 }
7818 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7819 return EXIT_FAILURE;
7820 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007821 /* TODO: bash prints a string representation
7822 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007823 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007824 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007825 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007826 }
7827
7828 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007829 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7830 for (i = 0; i < pi->num_cmds; i++) {
7831 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7832 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007833 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007834 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007835
7836 i = kill(- pi->pgrp, SIGCONT);
7837 if (i < 0) {
7838 if (errno == ESRCH) {
7839 delete_finished_bg_job(pi);
7840 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007841 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007842 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007843 }
7844
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007845 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007846 remove_bg_job(pi);
7847 return checkjobs_and_fg_shell(pi);
7848 }
7849 return EXIT_SUCCESS;
7850}
7851#endif
7852
7853#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007854static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007855{
7856 const struct built_in_command *x;
7857
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007858 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007859 "Built-in commands:\n"
7860 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007861 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01007862 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007863 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007864 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007865 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007866 return EXIT_SUCCESS;
7867}
7868#endif
7869
7870#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007871static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007872{
7873 struct pipe *job;
7874 const char *status_string;
7875
Denis Vlasenko87a86552008-07-29 19:43:10 +00007876 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007877 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007878 status_string = "Stopped";
7879 else
7880 status_string = "Running";
7881
7882 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7883 }
7884 return EXIT_SUCCESS;
7885}
7886#endif
7887
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007888#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007889static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007890{
7891 void *p;
7892 unsigned long l;
7893
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007894# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02007895 /* Optional. Reduces probability of false positives */
7896 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007897# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007898 /* Crude attempt to find where "free memory" starts,
7899 * sans fragmentation. */
7900 p = malloc(240);
7901 l = (unsigned long)p;
7902 free(p);
7903 p = malloc(3400);
7904 if (l < (unsigned long)p) l = (unsigned long)p;
7905 free(p);
7906
7907 if (!G.memleak_value)
7908 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007909
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007910 l -= G.memleak_value;
7911 if ((long)l < 0)
7912 l = 0;
7913 l /= 1024;
7914 if (l > 127)
7915 l = 127;
7916
7917 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7918 return l;
7919}
7920#endif
7921
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007922static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007923{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007924 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007925 return EXIT_SUCCESS;
7926}
7927
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007928static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007929{
Denys Vlasenko03dad222010-01-12 23:29:57 +01007930 const char *r;
7931 char *opt_n = NULL;
7932 char *opt_p = NULL;
7933 char *opt_t = NULL;
7934 char *opt_u = NULL;
7935 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007936
Denys Vlasenko03dad222010-01-12 23:29:57 +01007937 /* "!": do not abort on errors.
7938 * Option string must start with "sr" to match BUILTIN_READ_xxx
7939 */
7940 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
7941 if (read_flags == (uint32_t)-1)
7942 return EXIT_FAILURE;
7943 argv += optind;
7944
7945 r = shell_builtin_read(set_local_var_from_halves,
7946 argv,
7947 get_local_var_value("IFS"), /* can be NULL */
7948 read_flags,
7949 opt_n,
7950 opt_p,
7951 opt_t,
7952 opt_u
7953 );
7954
7955 if ((uintptr_t)r > 1) {
7956 bb_error_msg("%s", r);
7957 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007958 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007959
Denys Vlasenko03dad222010-01-12 23:29:57 +01007960 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007961}
7962
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007963/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7964 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007965 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007966 * set [-abCefhmnuvx] [-o option] [argument...]
7967 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007968 * set -- [argument...]
7969 * set -o
7970 * set +o
7971 * Implementations shall support the options in both their hyphen and
7972 * plus-sign forms. These options can also be specified as options to sh.
7973 * Examples:
7974 * Write out all variables and their values: set
7975 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7976 * Turn on the -x and -v options: set -xv
7977 * Unset all positional parameters: set --
7978 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7979 * Set the positional parameters to the expansion of x, even if x expands
7980 * with a leading '-' or '+': set -- $x
7981 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007982 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007983 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007984static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007985{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007986 int n;
7987 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007988 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007989
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007990 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007991 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007992 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007993 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007994 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007995 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007996
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007997 do {
7998 if (!strcmp(arg, "--")) {
7999 ++argv;
8000 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008001 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008002 if (arg[0] != '+' && arg[0] != '-')
8003 break;
8004 for (n = 1; arg[n]; ++n)
8005 if (set_mode(arg[0], arg[n]))
8006 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008007 } while ((arg = *++argv) != NULL);
8008 /* Now argv[0] is 1st argument */
8009
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008010 if (arg == NULL)
8011 return EXIT_SUCCESS;
8012 set_argv:
8013
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008014 /* NB: G.global_argv[0] ($0) is never freed/changed */
8015 g_argv = G.global_argv;
8016 if (G.global_args_malloced) {
8017 pp = g_argv;
8018 while (*++pp)
8019 free(*pp);
8020 g_argv[1] = NULL;
8021 } else {
8022 G.global_args_malloced = 1;
8023 pp = xzalloc(sizeof(pp[0]) * 2);
8024 pp[0] = g_argv[0]; /* retain $0 */
8025 g_argv = pp;
8026 }
8027 /* This realloc's G.global_argv */
8028 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8029
8030 n = 1;
8031 while (*++pp)
8032 n++;
8033 G.global_argc = n;
8034
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008035 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008036
8037 /* Nothing known, so abort */
8038 error:
8039 bb_error_msg("set: %s: invalid option", arg);
8040 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008041}
8042
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008043static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008044{
8045 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008046 argv = skip_dash_dash(argv);
8047 if (argv[0]) {
8048 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008049 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008050 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008051 if (G.global_args_malloced) {
8052 int m = 1;
8053 while (m <= n)
8054 free(G.global_argv[m++]);
8055 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008056 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008057 memmove(&G.global_argv[1], &G.global_argv[n+1],
8058 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008059 return EXIT_SUCCESS;
8060 }
8061 return EXIT_FAILURE;
8062}
8063
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008064static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008065{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008066 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008067 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008068 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008069#if ENABLE_HUSH_FUNCTIONS
8070 smallint sv_flg;
8071#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008072
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008073 argv = skip_dash_dash(argv);
8074 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008075 if (!filename) {
8076 /* bash says: "bash: .: filename argument required" */
8077 return 2; /* bash compat */
8078 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008079 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008080 if (!strchr(filename, '/')) {
8081 arg_path = find_in_path(filename);
8082 if (arg_path)
8083 filename = arg_path;
8084 }
8085 input = fopen_or_warn(filename, "r");
8086 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008087 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008088 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008089 return EXIT_FAILURE;
8090 }
8091 close_on_exec_on(fileno(input));
8092
Mike Frysinger885b6f22009-04-18 21:04:25 +00008093#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008094 sv_flg = G.flag_return_in_progress;
8095 /* "we are inside sourced file, ok to use return" */
8096 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008097#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008098 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008099
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008100 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008101 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008102
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008103 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008104#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008105 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008106#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008107
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008108 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008109}
8110
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008111static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008112{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008113 int rc;
8114 mode_t mask;
8115
8116 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008117 argv = skip_dash_dash(argv);
8118 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008119 mode_t old_mask = mask;
8120
8121 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008122 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008123 mask ^= 0777;
8124 if (rc == 0) {
8125 mask = old_mask;
8126 /* bash messages:
8127 * bash: umask: 'q': invalid symbolic mode operator
8128 * bash: umask: 999: octal number out of range
8129 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008130 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008131 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008132 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008133 rc = 1;
8134 /* Mimic bash */
8135 printf("%04o\n", (unsigned) mask);
8136 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008137 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008138 umask(mask);
8139
8140 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008141}
8142
Mike Frysingerd690f682009-03-30 06:50:54 +00008143/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008144static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008145{
Mike Frysingerd690f682009-03-30 06:50:54 +00008146 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008147 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008148
Denis Vlasenko28e67962009-04-26 23:22:40 +00008149 /* "!": do not abort on errors */
8150 /* "+": stop at 1st non-option */
8151 opts = getopt32(argv, "!+vf");
8152 if (opts == (unsigned)-1)
8153 return EXIT_FAILURE;
8154 if (opts == 3) {
8155 bb_error_msg("unset: -v and -f are exclusive");
8156 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008157 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008158 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008159
8160 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008161 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008162 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008163 if (unset_local_var(*argv)) {
8164 /* unset <nonexistent_var> doesn't fail.
8165 * Error is when one tries to unset RO var.
8166 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008167 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008168 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008169 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008170#if ENABLE_HUSH_FUNCTIONS
8171 else {
8172 unset_func(*argv);
8173 }
8174#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008175 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008176 }
8177 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008178}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008179
Mike Frysinger56bdea12009-03-28 20:01:58 +00008180/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008181static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008182{
8183 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008184 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008185
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008186 argv = skip_dash_dash(argv);
8187 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008188 /* Don't care about wait results */
8189 /* Note 1: must wait until there are no more children */
8190 /* Note 2: must be interruptible */
8191 /* Examples:
8192 * $ sleep 3 & sleep 6 & wait
8193 * [1] 30934 sleep 3
8194 * [2] 30935 sleep 6
8195 * [1] Done sleep 3
8196 * [2] Done sleep 6
8197 * $ sleep 3 & sleep 6 & wait
8198 * [1] 30936 sleep 3
8199 * [2] 30937 sleep 6
8200 * [1] Done sleep 3
8201 * ^C <-- after ~4 sec from keyboard
8202 * $
8203 */
8204 sigaddset(&G.blocked_set, SIGCHLD);
8205 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8206 while (1) {
8207 checkjobs(NULL);
8208 if (errno == ECHILD)
8209 break;
8210 /* Wait for SIGCHLD or any other signal of interest */
8211 /* sigtimedwait with infinite timeout: */
8212 sig = sigwaitinfo(&G.blocked_set, NULL);
8213 if (sig > 0) {
8214 sig = check_and_run_traps(sig);
8215 if (sig && sig != SIGCHLD) { /* see note 2 */
8216 ret = 128 + sig;
8217 break;
8218 }
8219 }
8220 }
8221 sigdelset(&G.blocked_set, SIGCHLD);
8222 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8223 return ret;
8224 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008225
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008226 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008227 while (*argv) {
8228 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008229 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008230 /* mimic bash message */
8231 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008232 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008233 }
8234 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008235 if (WIFSIGNALED(status))
8236 ret = 128 + WTERMSIG(status);
8237 else if (WIFEXITED(status))
8238 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008239 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008240 ret = EXIT_FAILURE;
8241 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008242 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008243 ret = 127;
8244 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008245 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008246 }
8247
8248 return ret;
8249}
8250
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008251#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8252static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8253{
8254 if (argv[1]) {
8255 def = bb_strtou(argv[1], NULL, 10);
8256 if (errno || def < def_min || argv[2]) {
8257 bb_error_msg("%s: bad arguments", argv[0]);
8258 def = UINT_MAX;
8259 }
8260 }
8261 return def;
8262}
8263#endif
8264
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008265#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008266static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008267{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008268 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008269 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008270 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008271 return EXIT_SUCCESS; /* bash compat */
8272 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008273 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008274
8275 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8276 if (depth == UINT_MAX)
8277 G.flag_break_continue = BC_BREAK;
8278 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008279 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008280
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008281 return EXIT_SUCCESS;
8282}
8283
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008284static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008285{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008286 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8287 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008288}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008289#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008290
8291#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008292static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008293{
8294 int rc;
8295
8296 if (G.flag_return_in_progress != -1) {
8297 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8298 return EXIT_FAILURE; /* bash compat */
8299 }
8300
8301 G.flag_return_in_progress = 1;
8302
8303 /* bash:
8304 * out of range: wraps around at 256, does not error out
8305 * non-numeric param:
8306 * f() { false; return qwe; }; f; echo $?
8307 * bash: return: qwe: numeric argument required <== we do this
8308 * 255 <== we also do this
8309 */
8310 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8311 return rc;
8312}
8313#endif