blob: 0333395f8e383ad60c740a23a8d763fd60884d7e [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 *
Mike Frysinger25a6ca02009-03-28 13:59:26 +000040 * POSIX syntax not implemented:
Eric Andersen78a7c992001-05-15 16:30:25 +000041 * aliases
Mike Frysinger25a6ca02009-03-28 13:59:26 +000042 * Tilde Expansion
Mike Frysinger25a6ca02009-03-28 13:59:26 +000043 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020044 * Bash compat TODO:
45 * redirection of stdout+stderr: &> and >&
46 * brace expansion: one/{two,three,four}
47 * reserved words: function select
48 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020049 * process substitution: <(list) and >(list)
50 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020051 * let EXPR [EXPR...]
52 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
53 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
54 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
55 * ((EXPR))
56 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020057 * This is exactly equivalent to let "EXPR".
58 * $[EXPR]: synonym for $((EXPR))
Mike Frysinger25a6ca02009-03-28 13:59:26 +000059 *
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000060 * TODOs:
61 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenko8806d642010-05-16 02:36:18 +020062 * special variables (done: PWD, PPID, RANDOM)
Eric Andersen25f27032001-04-26 23:22:31 +000063 * follow IFS rules more precisely, including update semantics
Denys Vlasenko08218012009-06-03 14:43:56 +020064 * export builtin should be special, its arguments are assignments
65 * and therefore expansion of them should be "one-word" expansion:
66 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
67 * compare with:
68 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
69 * ls: cannot access i=a: No such file or directory
70 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020072 * Note2: bash 3.2.33(1) does this only if export word itself
73 * is not quoted:
74 * $ export i=`echo 'aaa bbb'`; echo "$i"
75 * aaa bbb
76 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
77 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000078 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000079 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000080 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020081#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denys Vlasenko27726cb2009-09-12 14:48:33 +020082#include <malloc.h> /* for malloc_trim */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000083#include <glob.h>
84/* #include <dmalloc.h> */
85#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000086# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000087#endif
Denys Vlasenko03dad222010-01-12 23:29:57 +010088
89#include "shell_common.h"
90#include "builtin_read.h"
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010091#include "builtin_ulimit.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000092#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000093#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +020094#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +020095# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +020096#else
97# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +020098#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000099#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200100# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000101#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000102
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000103
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200104/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000105#define LEAK_HUNTING 0
106#define BUILD_AS_NOMMU 0
107/* Enable/disable sanity checks. Ok to enable in production,
108 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
109 * Keeping 1 for now even in released versions.
110 */
111#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200112/* Slightly bigger (+200 bytes), but faster hush.
113 * So far it only enables a trick with counting SIGCHLDs and forks,
114 * which allows us to do fewer waitpid's.
115 * (we can detect a case where neither forks were done nor SIGCHLDs happened
116 * and therefore waitpid will return the same result as last time)
117 */
118#define ENABLE_HUSH_FAST 0
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000119
120
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000121#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000122# undef BB_MMU
123# undef USE_FOR_NOMMU
124# undef USE_FOR_MMU
125# define BB_MMU 0
126# define USE_FOR_NOMMU(...) __VA_ARGS__
127# define USE_FOR_MMU(...)
128#endif
129
Denys Vlasenko14974842010-03-23 01:08:26 +0100130#define SKIP_definitions 1
131#include "applet_tables.h"
132#undef SKIP_definitions
133#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000134/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000135# undef CONFIG_FEATURE_SH_STANDALONE
136# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000137# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100138# undef IF_NOT_FEATURE_SH_STANDALONE
139# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000140# define IF_FEATURE_SH_STANDALONE(...)
141# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000142#endif
143
Denis Vlasenko05743d72008-02-10 12:10:08 +0000144#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000145# undef ENABLE_FEATURE_EDITING
146# define ENABLE_FEATURE_EDITING 0
147# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
148# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000149#endif
150
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000151/* Do we support ANY keywords? */
152#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000153# define HAS_KEYWORDS 1
154# define IF_HAS_KEYWORDS(...) __VA_ARGS__
155# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000156#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000157# define HAS_KEYWORDS 0
158# define IF_HAS_KEYWORDS(...)
159# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000160#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000161
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000162/* If you comment out one of these below, it will be #defined later
163 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000164#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000165/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000166#define debug_printf_parse(...) do {} while (0)
167#define debug_print_tree(a, b) do {} while (0)
168#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000169#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000170#define debug_printf_jobs(...) do {} while (0)
171#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000172#define debug_printf_glob(...) do {} while (0)
173#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000174#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000175#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000176
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000177#define ERR_PTR ((void*)(long)1)
178
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000179#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000180
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000181#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000182
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200183struct variable;
184
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000185static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
186
187/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000188 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000189 */
190#if !BB_MMU
191typedef struct nommu_save_t {
192 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200193 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000194 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000195 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000196} nommu_save_t;
197#endif
198
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000199typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000200 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000201#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000202 RES_IF ,
203 RES_THEN ,
204 RES_ELIF ,
205 RES_ELSE ,
206 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000207#endif
208#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000209 RES_FOR ,
210 RES_WHILE ,
211 RES_UNTIL ,
212 RES_DO ,
213 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000214#endif
215#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000216 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000217#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000218#if ENABLE_HUSH_CASE
219 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200220 /* three pseudo-keywords support contrived "case" syntax: */
221 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
222 RES_MATCH , /* "word)" */
223 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000224 RES_ESAC ,
225#endif
226 RES_XXXX ,
227 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000228} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000229
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000230typedef struct o_string {
231 char *data;
232 int length; /* position where data is appended */
233 int maxlen;
234 /* Protect newly added chars against globbing
235 * (by prepending \ to *, ?, [, \) */
236 smallint o_escape;
237 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000238 /* At least some part of the string was inside '' or "",
239 * possibly empty one: word"", wo''rd etc. */
240 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000241 smallint has_empty_slot;
242 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
243} o_string;
244enum {
245 MAYBE_ASSIGNMENT = 0,
246 DEFINITELY_ASSIGNMENT = 1,
247 NOT_ASSIGNMENT = 2,
248 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
249};
250/* Used for initialization: o_string foo = NULL_O_STRING; */
251#define NULL_O_STRING { NULL }
252
253/* I can almost use ordinary FILE*. Is open_memstream() universally
254 * available? Where is it documented? */
255typedef struct in_str {
256 const char *p;
257 /* eof_flag=1: last char in ->p is really an EOF */
258 char eof_flag; /* meaningless if ->p == NULL */
259 char peek_buf[2];
260#if ENABLE_HUSH_INTERACTIVE
261 smallint promptme;
262 smallint promptmode; /* 0: PS1, 1: PS2 */
263#endif
264 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200265 int (*get) (struct in_str *) FAST_FUNC;
266 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000267} in_str;
268#define i_getch(input) ((input)->get(input))
269#define i_peek(input) ((input)->peek(input))
270
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200271/* The descrip member of this structure is only used to make
272 * debugging output pretty */
273static const struct {
274 int mode;
275 signed char default_fd;
276 char descrip[3];
277} redir_table[] = {
278 { O_RDONLY, 0, "<" },
279 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
280 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
281 { O_CREAT|O_RDWR, 1, "<>" },
282 { O_RDONLY, 0, "<<" },
283/* Should not be needed. Bogus default_fd helps in debugging */
284/* { O_RDONLY, 77, "<<" }, */
285};
286
Eric Andersen25f27032001-04-26 23:22:31 +0000287struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000288 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000289 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000290 int rd_fd; /* fd to redirect */
291 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
292 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000293 smallint rd_type; /* (enum redir_type) */
294 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000295 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200296 * bit 0: do we need to trim leading tabs?
297 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000298 */
Eric Andersen25f27032001-04-26 23:22:31 +0000299};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000300typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200301 REDIRECT_INPUT = 0,
302 REDIRECT_OVERWRITE = 1,
303 REDIRECT_APPEND = 2,
304 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000305 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200306 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000307
308 REDIRFD_CLOSE = -3,
309 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000310 REDIRFD_TO_FILE = -1,
311 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000312
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000313 HEREDOC_SKIPTABS = 1,
314 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000315} redir_type;
316
Eric Andersen25f27032001-04-26 23:22:31 +0000317
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000318struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000319 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000320 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000321 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200322 smallint cmd_type; /* CMD_xxx */
323#define CMD_NORMAL 0
324#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200325
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200326/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200327#if ENABLE_HUSH_BASH_COMPAT
328# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000329#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200330
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200331/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200332//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200333// It is hard to implement correctly, it adds significant amounts of tricky code,
334// and all this is only useful for really obscure export statements
335// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
336// guards the code which implements it, but I have doubts it works
337// in all cases (especially with mixed globbed/non-globbed arguments)
338
339#if ENABLE_HUSH_FUNCTIONS
340# define CMD_FUNCDEF 3
341#endif
342
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200343 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
344 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000345#if !BB_MMU
346 char *group_as_string;
347#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000348#if ENABLE_HUSH_FUNCTIONS
349 struct function *child_func;
350/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200351 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000352 * When we execute "f1() {a;}" cmd, we create new function and clear
353 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200354 * When we execute "f1() {b;}", we notice that f1 exists,
355 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000356 * we put those fields back into cmd->xxx
357 * (struct function has ->parent_cmd ptr to facilitate that).
358 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
359 * Without this trick, loop would execute a;b;b;b;...
360 * instead of correct sequence a;b;a;b;...
361 * When command is freed, it severs the link
362 * (sets ->child_func->parent_cmd to NULL).
363 */
364#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000365 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000366/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
367 * and on execution these are substituted with their values.
368 * Substitution can make _several_ words out of one argv[n]!
369 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000370 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000371 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000372 struct redir_struct *redirects; /* I/O redirections */
373};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000374/* Is there anything in this command at all? */
375#define IS_NULL_CMD(cmd) \
376 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
377
Eric Andersen25f27032001-04-26 23:22:31 +0000378
379struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000380 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000381 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000382 int alive_cmds; /* number of commands running (not exited) */
383 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000384#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000385 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000386 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000387 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000388#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000389 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000390 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000391 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
392 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000393};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000394typedef enum pipe_style {
395 PIPE_SEQ = 1,
396 PIPE_AND = 2,
397 PIPE_OR = 3,
398 PIPE_BG = 4,
399} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000400/* Is there anything in this pipe at all? */
401#define IS_NULL_PIPE(pi) \
402 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000403
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000404/* This holds pointers to the various results of parsing */
405struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000406 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000407 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000408 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000409 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000410 /* last command in pipe (being constructed right now) */
411 struct command *command;
412 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000413 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000414#if !BB_MMU
415 o_string as_string;
416#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000417#if HAS_KEYWORDS
418 smallint ctx_res_w;
419 smallint ctx_inverted; /* "! cmd | cmd" */
420#if ENABLE_HUSH_CASE
421 smallint ctx_dsemicolon; /* ";;" seen */
422#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000423 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
424 int old_flag;
425 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000426 * example: "if pipe1; pipe2; then pipe3; fi"
427 * when we see "if" or "then", we malloc and copy current context,
428 * and make ->stack point to it. then we parse pipeN.
429 * when closing "then" / fi" / whatever is found,
430 * we move list_head into ->stack->command->group,
431 * copy ->stack into current context, and delete ->stack.
432 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000433 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000434 struct parse_context *stack;
435#endif
436};
437
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000438/* On program start, environ points to initial environment.
439 * putenv adds new pointers into it, unsetenv removes them.
440 * Neither of these (de)allocates the strings.
441 * setenv allocates new strings in malloc space and does putenv,
442 * and thus setenv is unusable (leaky) for shell's purposes */
443#define setenv(...) setenv_is_leaky_dont_use()
444struct variable {
445 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000446 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200447#if ENABLE_HUSH_LOCAL
448 unsigned func_nest_level;
449#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000450 int max_len; /* if > 0, name is part of initial env; else name is malloced */
451 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000452 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000453};
454
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000455enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000456 BC_BREAK = 1,
457 BC_CONTINUE = 2,
458};
459
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000460#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000461struct function {
462 struct function *next;
463 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000464 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000465 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200466# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000467 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200468# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000469};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000470#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000471
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000472
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000473/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000474/* Sorted roughly by size (smaller offsets == smaller code) */
475struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000476 /* interactive_fd != 0 means we are an interactive shell.
477 * If we are, then saved_tty_pgrp can also be != 0, meaning
478 * that controlling tty is available. With saved_tty_pgrp == 0,
479 * job control still works, but terminal signals
480 * (^C, ^Z, ^Y, ^\) won't work at all, and background
481 * process groups can only be created with "cmd &".
482 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
483 * to give tty to the foreground process group,
484 * and will take it back when the group is stopped (^Z)
485 * or killed (^C).
486 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000487#if ENABLE_HUSH_INTERACTIVE
488 /* 'interactive_fd' is a fd# open to ctty, if we have one
489 * _AND_ if we decided to act interactively */
490 int interactive_fd;
491 const char *PS1;
492 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000493# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000494#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000495# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000496#endif
497#if ENABLE_FEATURE_EDITING
498 line_input_t *line_input_state;
499#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000500 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200501 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000502 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200503#if ENABLE_HUSH_RANDOM_SUPPORT
504 random_t random_gen;
505#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000506#if ENABLE_HUSH_JOB
507 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000508 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000509 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000510 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400511# define G_saved_tty_pgrp (G.saved_tty_pgrp)
512#else
513# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000514#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000515 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000516#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000517 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000518#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000519#if ENABLE_HUSH_FUNCTIONS
520 /* 0: outside of a function (or sourced file)
521 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000522 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000523 */
524 smallint flag_return_in_progress;
525#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000526 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000527 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000528 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000529 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000530 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000531 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100532 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000533 /* how many non-NULL argv's we have. NB: $# + 1 */
534 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000535 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000536#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000537 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000538#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000539#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000540 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000541 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000542#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000543 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000544 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000545 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000546 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000547#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000548 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200549# if ENABLE_HUSH_LOCAL
550 struct variable **shadowed_vars_pp;
551 unsigned func_nest_level;
552# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000553#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000554 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200555#if ENABLE_HUSH_FAST
556 unsigned count_SIGCHLD;
557 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200558 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200559#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000560 /* which signals have non-DFL handler (even with no traps set)? */
561 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000562 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000563 sigset_t blocked_set;
564 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000565#if HUSH_DEBUG
566 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000567 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000568#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200569 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000570};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000571#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000572/* Not #defining name to G.name - this quickly gets unwieldy
573 * (too many defines). Also, I actually prefer to see when a variable
574 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000575#define INIT_G() do { \
576 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
577} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000578
579
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000580/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200581static int builtin_cd(char **argv) FAST_FUNC;
582static int builtin_echo(char **argv) FAST_FUNC;
583static int builtin_eval(char **argv) FAST_FUNC;
584static int builtin_exec(char **argv) FAST_FUNC;
585static int builtin_exit(char **argv) FAST_FUNC;
586static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000587#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200588static int builtin_fg_bg(char **argv) FAST_FUNC;
589static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000590#endif
591#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200592static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000593#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200594#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200595static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200596#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000597#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200598static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000599#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400600#if ENABLE_PRINTF
601static int builtin_printf(char **argv) FAST_FUNC;
602#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200603static int builtin_pwd(char **argv) FAST_FUNC;
604static int builtin_read(char **argv) FAST_FUNC;
605static int builtin_set(char **argv) FAST_FUNC;
606static int builtin_shift(char **argv) FAST_FUNC;
607static int builtin_source(char **argv) FAST_FUNC;
608static int builtin_test(char **argv) FAST_FUNC;
609static int builtin_trap(char **argv) FAST_FUNC;
610static int builtin_type(char **argv) FAST_FUNC;
611static int builtin_true(char **argv) FAST_FUNC;
612static int builtin_umask(char **argv) FAST_FUNC;
613static int builtin_unset(char **argv) FAST_FUNC;
614static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000615#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200616static int builtin_break(char **argv) FAST_FUNC;
617static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000618#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000619#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200620static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000621#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000622
623/* Table of built-in functions. They can be forked or not, depending on
624 * context: within pipes, they fork. As simple commands, they do not.
625 * When used in non-forking context, they can change global variables
626 * in the parent shell process. If forked, of course they cannot.
627 * For example, 'unset foo | whatever' will parse and run, but foo will
628 * still be set at the end. */
629struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100630 const char *b_cmd;
631 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000632#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100633 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200634# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000635#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200636# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000637#endif
638};
639
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200640static const struct built_in_command bltins1[] = {
641 BLTIN("." , builtin_source , "Run commands in a file"),
642 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000643#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200644 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000645#endif
646#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200647 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000648#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200649 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000650#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200651 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000652#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200653 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
654 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
655 BLTIN("exit" , builtin_exit , "Exit"),
656 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000657#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200658 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000659#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000660#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200661 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000662#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000663#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200664 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000665#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200666#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200667 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200668#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000669#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200670 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000671#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200672 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000673#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200674 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000675#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200676 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
677 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200678#if ENABLE_HUSH_BASH_COMPAT
679 BLTIN("source" , builtin_source , "Run commands in a file"),
680#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200681 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100682 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100683 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200684 BLTIN("umask" , builtin_umask , "Set file creation mask"),
685 BLTIN("unset" , builtin_unset , "Unset variables"),
686 BLTIN("wait" , builtin_wait , "Wait for process"),
687};
688/* For now, echo and test are unconditionally enabled.
689 * Maybe make it configurable? */
690static const struct built_in_command bltins2[] = {
691 BLTIN("[" , builtin_test , NULL),
692 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400693#if ENABLE_PRINTF
694 BLTIN("printf" , builtin_printf , NULL),
695#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200696 BLTIN("pwd" , builtin_pwd , NULL),
697 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000698};
699
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000700
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000701/* Debug printouts.
702 */
703#if HUSH_DEBUG
704/* prevent disasters with G.debug_indent < 0 */
705# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
706# define debug_enter() (G.debug_indent++)
707# define debug_leave() (G.debug_indent--)
708#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200709# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000710# define debug_enter() ((void)0)
711# define debug_leave() ((void)0)
712#endif
713
714#ifndef debug_printf
715# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
716#endif
717
718#ifndef debug_printf_parse
719# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
720#endif
721
722#ifndef debug_printf_exec
723#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
724#endif
725
726#ifndef debug_printf_env
727# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
728#endif
729
730#ifndef debug_printf_jobs
731# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
732# define DEBUG_JOBS 1
733#else
734# define DEBUG_JOBS 0
735#endif
736
737#ifndef debug_printf_expand
738# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
739# define DEBUG_EXPAND 1
740#else
741# define DEBUG_EXPAND 0
742#endif
743
744#ifndef debug_printf_glob
745# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
746# define DEBUG_GLOB 1
747#else
748# define DEBUG_GLOB 0
749#endif
750
751#ifndef debug_printf_list
752# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
753#endif
754
755#ifndef debug_printf_subst
756# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
757#endif
758
759#ifndef debug_printf_clean
760# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
761# define DEBUG_CLEAN 1
762#else
763# define DEBUG_CLEAN 0
764#endif
765
766#if DEBUG_EXPAND
767static void debug_print_strings(const char *prefix, char **vv)
768{
769 indent();
770 fprintf(stderr, "%s:\n", prefix);
771 while (*vv)
772 fprintf(stderr, " '%s'\n", *vv++);
773}
774#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200775# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000776#endif
777
778
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000779/* Leak hunting. Use hush_leaktool.sh for post-processing.
780 */
781#if LEAK_HUNTING
782static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000783{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000784 void *ptr = xmalloc((size + 0xff) & ~0xff);
785 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
786 return ptr;
787}
788static void *xxrealloc(int lineno, void *ptr, size_t size)
789{
790 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
791 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
792 return ptr;
793}
794static char *xxstrdup(int lineno, const char *str)
795{
796 char *ptr = xstrdup(str);
797 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
798 return ptr;
799}
800static void xxfree(void *ptr)
801{
802 fdprintf(2, "free %p\n", ptr);
803 free(ptr);
804}
805#define xmalloc(s) xxmalloc(__LINE__, s)
806#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
807#define xstrdup(s) xxstrdup(__LINE__, s)
808#define free(p) xxfree(p)
809#endif
810
811
812/* Syntax and runtime errors. They always abort scripts.
813 * In interactive use they usually discard unparsed and/or unexecuted commands
814 * and return to the prompt.
815 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
816 */
817#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200818# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000819# define syntax_error(lineno, msg) syntax_error(msg)
820# define syntax_error_at(lineno, msg) syntax_error_at(msg)
821# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
822# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
823# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000824#endif
825
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000826static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000827{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000828 va_list p;
829
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000830#if HUSH_DEBUG >= 2
831 bb_error_msg("hush.c:%u", lineno);
832#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000833 va_start(p, fmt);
834 bb_verror_msg(fmt, p, NULL);
835 va_end(p);
836 if (!G_interactive_fd)
837 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000838}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000839
840static void syntax_error(unsigned lineno, const char *msg)
841{
842 if (msg)
843 die_if_script(lineno, "syntax error: %s", msg);
844 else
845 die_if_script(lineno, "syntax error", NULL);
846}
847
848static void syntax_error_at(unsigned lineno, const char *msg)
849{
850 die_if_script(lineno, "syntax error at '%s'", msg);
851}
852
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400853static void syntax_error_unterm_str(unsigned lineno, const char *s)
854{
855 die_if_script(lineno, "syntax error: unterminated %s", s);
856}
857
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000858/* It so happens that all such cases are totally fatal
859 * even if shell is interactive: EOF while looking for closing
860 * delimiter. There is nowhere to read stuff from after that,
861 * it's EOF! The only choice is to terminate.
862 */
863static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000864static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000865{
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400866 char msg[2] = { ch, '\0' };
867 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000868 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000869}
870
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200871static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000872{
873 char msg[2];
874 msg[0] = ch;
875 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200876 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000877}
878
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000879#if HUSH_DEBUG < 2
880# undef die_if_script
881# undef syntax_error
882# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000883# undef syntax_error_unterm_ch
884# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000885# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000886#else
Denys Vlasenko606291b2009-09-23 23:15:43 +0200887# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000888# define syntax_error(msg) syntax_error(__LINE__, msg)
889# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
890# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
891# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
892# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000893#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000894
Denis Vlasenko552433b2009-04-04 19:29:21 +0000895
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000896#if ENABLE_HUSH_INTERACTIVE
897static void cmdedit_update_prompt(void);
898#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200899# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000900#endif
901
902
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000903/* Utility functions
904 */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000905/* Replace each \x with x in place, return ptr past NUL. */
906static char *unbackslash(char *src)
907{
Denys Vlasenko71885402009-09-24 01:44:13 +0200908 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +0000909 while (1) {
910 if (*src == '\\')
911 src++;
912 if ((*dst++ = *src++) == '\0')
913 break;
914 }
915 return dst;
916}
917
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000918static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000919{
920 int i;
921 unsigned count1;
922 unsigned count2;
923 char **v;
924
925 v = strings;
926 count1 = 0;
927 if (v) {
928 while (*v) {
929 count1++;
930 v++;
931 }
932 }
933 count2 = 0;
934 v = add;
935 while (*v) {
936 count2++;
937 v++;
938 }
939 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
940 v[count1 + count2] = NULL;
941 i = count2;
942 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000943 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000944 return v;
945}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000946#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000947static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
948{
949 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
950 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
951 return ptr;
952}
953#define add_strings_to_strings(strings, add, need_to_dup) \
954 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
955#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000956
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200957/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000958static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000959{
960 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000961 v[0] = add;
962 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000963 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000964}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000965#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000966static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
967{
968 char **ptr = add_string_to_strings(strings, add);
969 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
970 return ptr;
971}
972#define add_string_to_strings(strings, add) \
973 xx_add_string_to_strings(__LINE__, strings, add)
974#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000975
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200976static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000977{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000978 char **v;
979
980 if (!strings)
981 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000982 v = strings;
983 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200984 free(*v);
985 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000986 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000987 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000988}
989
Denis Vlasenko76d50412008-06-10 16:19:39 +0000990
Denis Vlasenko270b1c32009-04-17 18:54:50 +0000991/* Helpers for setting new $n and restoring them back
992 */
993typedef struct save_arg_t {
994 char *sv_argv0;
995 char **sv_g_argv;
996 int sv_g_argc;
997 smallint sv_g_malloced;
998} save_arg_t;
999
1000static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1001{
1002 int n;
1003
1004 sv->sv_argv0 = argv[0];
1005 sv->sv_g_argv = G.global_argv;
1006 sv->sv_g_argc = G.global_argc;
1007 sv->sv_g_malloced = G.global_args_malloced;
1008
1009 argv[0] = G.global_argv[0]; /* retain $0 */
1010 G.global_argv = argv;
1011 G.global_args_malloced = 0;
1012
1013 n = 1;
1014 while (*++argv)
1015 n++;
1016 G.global_argc = n;
1017}
1018
1019static void restore_G_args(save_arg_t *sv, char **argv)
1020{
1021 char **pp;
1022
1023 if (G.global_args_malloced) {
1024 /* someone ran "set -- arg1 arg2 ...", undo */
1025 pp = G.global_argv;
1026 while (*++pp) /* note: does not free $0 */
1027 free(*pp);
1028 free(G.global_argv);
1029 }
1030 argv[0] = sv->sv_argv0;
1031 G.global_argv = sv->sv_g_argv;
1032 G.global_argc = sv->sv_g_argc;
1033 G.global_args_malloced = sv->sv_g_malloced;
1034}
1035
1036
Denis Vlasenkod5762932009-03-31 11:22:57 +00001037/* Basic theory of signal handling in shell
1038 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001039 * This does not describe what hush does, rather, it is current understanding
1040 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001041 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1042 *
1043 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1044 * is finished or backgrounded. It is the same in interactive and
1045 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001046 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001047 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001048 * backgrounds (i.e. stops) or kills all members of currently running
1049 * pipe.
1050 *
1051 * Wait builtin in interruptible by signals for which user trap is set
1052 * or by SIGINT in interactive shell.
1053 *
1054 * Trap handlers will execute even within trap handlers. (right?)
1055 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001056 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1057 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001058 *
1059 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001060 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001061 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001062 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001063 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001064 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001065 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001066 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001067 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001068 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001069 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001070 *
1071 * SIGQUIT: ignore
1072 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001073 * SIGHUP (interactive):
1074 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001075 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001076 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1077 * that all pipe members are stopped. Try this in bash:
1078 * while :; do :; done - ^Z does not background it
1079 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001080 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001081 * of the command line, show prompt. NB: ^C does not send SIGINT
1082 * to interactive shell while shell is waiting for a pipe,
1083 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001084 * Example 1: this waits 5 sec, but does not execute ls:
1085 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1086 * Example 2: this does not wait and does not execute ls:
1087 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1088 * Example 3: this does not wait 5 sec, but executes ls:
1089 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001090 *
1091 * (What happens to signals which are IGN on shell start?)
1092 * (What happens with signal mask on shell start?)
1093 *
1094 * Implementation in hush
1095 * ======================
1096 * We use in-kernel pending signal mask to determine which signals were sent.
1097 * We block all signals which we don't want to take action immediately,
1098 * i.e. we block all signals which need to have special handling as described
1099 * above, and all signals which have traps set.
1100 * After each pipe execution, we extract any pending signals via sigtimedwait()
1101 * and act on them.
1102 *
1103 * unsigned non_DFL_mask: a mask of such "special" signals
1104 * sigset_t blocked_set: current blocked signal set
1105 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001106 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001107 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001108 * "trap 'cmd' SIGxxx":
1109 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001110 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001111 * unblock signals with special interactive handling
1112 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001113 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001114 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001115 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001116 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001117 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001118 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001119 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001120 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001121 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001122 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001123 * Standard says "When a subshell is entered, traps that are not being ignored
1124 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001125 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001126 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001127enum {
1128 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001129 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001130 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001131 | (1 << SIGHUP)
1132 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001133 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001134#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001135 | (1 << SIGTTIN)
1136 | (1 << SIGTTOU)
1137 | (1 << SIGTSTP)
1138#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001139};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001140
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001141#if ENABLE_HUSH_FAST
1142static void SIGCHLD_handler(int sig UNUSED_PARAM)
1143{
1144 G.count_SIGCHLD++;
1145//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1146}
1147#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001148
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001149#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001150
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001151/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1152#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001153/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001154#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1155
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001156/* Restores tty foreground process group, and exits.
1157 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001158 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001159 * or called directly with -EXITCODE.
1160 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001161static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001162static void sigexit(int sig)
1163{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001164 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001165 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001166
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001167 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001168 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001169 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1170 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001171
1172 /* Not a signal, just exit */
1173 if (sig <= 0)
1174 _exit(- sig);
1175
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001176 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001177}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001178#else
1179
1180#define disable_restore_tty_pgrp_on_exit() ((void)0)
1181#define enable_restore_tty_pgrp_on_exit() ((void)0)
1182
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001183#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001184
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001185/* Restores tty foreground process group, and exits. */
1186static void hush_exit(int exitcode) NORETURN;
1187static void hush_exit(int exitcode)
1188{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001189 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1190 /* Prevent recursion:
1191 * trap "echo Hi; exit" EXIT; exit
1192 */
1193 char *argv[] = { NULL, G.traps[0], NULL };
1194 G.traps[0] = NULL;
1195 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001196 builtin_eval(argv);
1197 free(argv[1]);
1198 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001199
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001200#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001201 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001202 sigexit(- (exitcode & 0xff));
1203#else
1204 exit(exitcode);
1205#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001206}
1207
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001208static int check_and_run_traps(int sig)
1209{
1210 static const struct timespec zero_timespec = { 0, 0 };
1211 smalluint save_rcode;
1212 int last_sig = 0;
1213
1214 if (sig)
1215 goto jump_in;
1216 while (1) {
1217 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1218 if (sig <= 0)
1219 break;
1220 jump_in:
1221 last_sig = sig;
1222 if (G.traps && G.traps[sig]) {
1223 if (G.traps[sig][0]) {
1224 /* We have user-defined handler */
1225 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1226 save_rcode = G.last_exitcode;
1227 builtin_eval(argv);
1228 free(argv[1]);
1229 G.last_exitcode = save_rcode;
1230 } /* else: "" trap, ignoring signal */
1231 continue;
1232 }
1233 /* not a trap: special action */
1234 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001235#if ENABLE_HUSH_FAST
1236 case SIGCHLD:
1237 G.count_SIGCHLD++;
1238//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1239 break;
1240#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001241 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001242 /* Builtin was ^C'ed, make it look prettier: */
1243 bb_putchar('\n');
1244 G.flag_SIGINT = 1;
1245 break;
1246#if ENABLE_HUSH_JOB
1247 case SIGHUP: {
1248 struct pipe *job;
1249 /* bash is observed to signal whole process groups,
1250 * not individual processes */
1251 for (job = G.job_list; job; job = job->next) {
1252 if (job->pgrp <= 0)
1253 continue;
1254 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1255 if (kill(- job->pgrp, SIGHUP) == 0)
1256 kill(- job->pgrp, SIGCONT);
1257 }
1258 sigexit(SIGHUP);
1259 }
1260#endif
1261 default: /* ignored: */
1262 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1263 break;
1264 }
1265 }
1266 return last_sig;
1267}
1268
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001269
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001270static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001271{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001272 if (force || G.cwd == NULL) {
1273 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1274 * we must not try to free(bb_msg_unknown) */
1275 if (G.cwd == bb_msg_unknown)
1276 G.cwd = NULL;
1277 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1278 if (!G.cwd)
1279 G.cwd = bb_msg_unknown;
1280 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001281 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001282}
1283
Denis Vlasenko83506862007-11-23 13:11:42 +00001284
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001285/*
1286 * Shell and environment variable support
1287 */
1288static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001289{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001290 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001291 struct variable *cur;
1292 int len;
1293
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001294 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001295 pp = &G.top_var;
1296 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001297 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001298 return pp;
1299 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001300 }
1301 return NULL;
1302}
1303
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001304static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001305{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001306 struct variable **pp = get_ptr_to_local_var(name);
1307 if (pp)
1308 return *pp;
1309 return NULL;
1310}
1311
Denys Vlasenko03dad222010-01-12 23:29:57 +01001312static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001313{
1314 struct variable **pp = get_ptr_to_local_var(name);
1315 if (pp)
1316 return strchr((*pp)->varstr, '=') + 1;
Denys Vlasenkodea47882009-10-09 15:40:49 +02001317 if (strcmp(name, "PPID") == 0)
1318 return utoa(G.root_ppid);
1319 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001320#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001321 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001322 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001323 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001324#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001325 return NULL;
1326}
1327
1328/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001329 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001330 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001331 * 0: do not change export flag
1332 * (if creating new variable, flag will be 0)
1333 * 1: set export flag and putenv the variable
1334 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001335 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001336 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001337#if !BB_MMU && ENABLE_HUSH_LOCAL
1338/* all params are used */
1339#elif BB_MMU && ENABLE_HUSH_LOCAL
1340#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1341 set_local_var(str, flg_export, local_lvl)
1342#elif BB_MMU && !ENABLE_HUSH_LOCAL
1343#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001344 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001345#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1346#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1347 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001348#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001349static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001350{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001351 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001352 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001353 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001354 int name_len;
1355
Denis Vlasenko950bd722009-04-21 11:23:56 +00001356 eq_sign = strchr(str, '=');
1357 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001358 free(str);
1359 return -1;
1360 }
1361
Denis Vlasenko950bd722009-04-21 11:23:56 +00001362 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001363 var_pp = &G.top_var;
1364 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001365 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001366 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001367 continue;
1368 }
1369 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001370 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001371#if !BB_MMU
1372 if (!flg_read_only)
1373#endif
1374 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001375 free(str);
1376 return -1;
1377 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001378 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001379 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1380 *eq_sign = '\0';
1381 unsetenv(str);
1382 *eq_sign = '=';
1383 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001384#if ENABLE_HUSH_LOCAL
1385 if (cur->func_nest_level < local_lvl) {
1386 /* New variable is declared as local,
1387 * and existing one is global, or local
1388 * from enclosing function.
1389 * Remove and save old one: */
1390 *var_pp = cur->next;
1391 cur->next = *G.shadowed_vars_pp;
1392 *G.shadowed_vars_pp = cur;
1393 /* bash 3.2.33(1) and exported vars:
1394 * # export z=z
1395 * # f() { local z=a; env | grep ^z; }
1396 * # f
1397 * z=a
1398 * # env | grep ^z
1399 * z=z
1400 */
1401 if (cur->flg_export)
1402 flg_export = 1;
1403 break;
1404 }
1405#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001406 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001407 free_and_exp:
1408 free(str);
1409 goto exp;
1410 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001411 if (cur->max_len != 0) {
1412 if (cur->max_len >= strlen(str)) {
1413 /* This one is from startup env, reuse space */
1414 strcpy(cur->varstr, str);
1415 goto free_and_exp;
1416 }
1417 } else {
1418 /* max_len == 0 signifies "malloced" var, which we can
1419 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001420 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001421 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001422 cur->max_len = 0;
1423 goto set_str_and_exp;
1424 }
1425
Denys Vlasenko295fef82009-06-03 12:47:26 +02001426 /* Not found - create new variable struct */
1427 cur = xzalloc(sizeof(*cur));
1428#if ENABLE_HUSH_LOCAL
1429 cur->func_nest_level = local_lvl;
1430#endif
1431 cur->next = *var_pp;
1432 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001433
1434 set_str_and_exp:
1435 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001436#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001437 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001438#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001439 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001440 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001441 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001442 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1443 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001444 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001445 if (flg_export == -1) {
1446 cur->flg_export = 0;
1447 /* unsetenv was already done */
1448 } else {
1449 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1450 return putenv(cur->varstr);
1451 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001452 }
1453 return 0;
1454}
1455
Denys Vlasenko6db47842009-09-05 20:15:17 +02001456/* Used at startup and after each cd */
1457static void set_pwd_var(int exp)
1458{
1459 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1460 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1461}
1462
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001463static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001464{
1465 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001466 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001467
1468 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001469 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001470 var_pp = &G.top_var;
1471 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001472 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1473 if (cur->flg_read_only) {
1474 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001475 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001476 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001477 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001478 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1479 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001480 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1481 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001482 if (!cur->max_len)
1483 free(cur->varstr);
1484 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001485 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001486 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001487 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001488 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001489 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001490}
1491
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001492static int unset_local_var(const char *name)
1493{
1494 return unset_local_var_len(name, strlen(name));
1495}
1496
1497static void unset_vars(char **strings)
1498{
1499 char **v;
1500
1501 if (!strings)
1502 return;
1503 v = strings;
1504 while (*v) {
1505 const char *eq = strchrnul(*v, '=');
1506 unset_local_var_len(*v, (int)(eq - *v));
1507 v++;
1508 }
1509 free(strings);
1510}
1511
Mike Frysinger98c52642009-04-02 10:02:37 +00001512#if ENABLE_SH_MATH_SUPPORT
1513#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1514#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denys Vlasenko03dad222010-01-12 23:29:57 +01001515static char* FAST_FUNC endofname(const char *name)
Mike Frysinger98c52642009-04-02 10:02:37 +00001516{
1517 char *p;
1518
1519 p = (char *) name;
1520 if (!is_name(*p))
1521 return p;
1522 while (*++p) {
1523 if (!is_in_name(*p))
1524 break;
1525 }
1526 return p;
1527}
Denys Vlasenko6b01b712010-01-24 22:52:21 +01001528#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001529
Denys Vlasenko03dad222010-01-12 23:29:57 +01001530static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001531{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001532 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001533 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001534}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001535
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001536
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001537/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001538 * Helpers for "var1=val1 var2=val2 cmd" feature
1539 */
1540static void add_vars(struct variable *var)
1541{
1542 struct variable *next;
1543
1544 while (var) {
1545 next = var->next;
1546 var->next = G.top_var;
1547 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001548 if (var->flg_export) {
1549 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001550 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001551 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001552 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001553 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001554 var = next;
1555 }
1556}
1557
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001558static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001559{
1560 char **s;
1561 struct variable *old = NULL;
1562
1563 if (!strings)
1564 return old;
1565 s = strings;
1566 while (*s) {
1567 struct variable *var_p;
1568 struct variable **var_pp;
1569 char *eq;
1570
1571 eq = strchr(*s, '=');
1572 if (eq) {
1573 *eq = '\0';
1574 var_pp = get_ptr_to_local_var(*s);
1575 *eq = '=';
1576 if (var_pp) {
1577 /* Remove variable from global linked list */
1578 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001579 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001580 *var_pp = var_p->next;
1581 /* Add it to returned list */
1582 var_p->next = old;
1583 old = var_p;
1584 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001585 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001586 }
1587 s++;
1588 }
1589 return old;
1590}
1591
1592
1593/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001594 * in_str support
1595 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001596static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001597{
1598 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001599 if (ch != '\0')
1600 return ch;
1601 i->p--;
1602 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001603}
1604
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001605static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001606{
1607 return *i->p;
1608}
1609
1610#if ENABLE_HUSH_INTERACTIVE
1611
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001612static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001613{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001614 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001615 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001616 if (G.PS1 == NULL)
1617 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001618 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001619 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001620 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001621 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001622 if (G.PS2 == NULL)
1623 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001624}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001625
1626static const char* setup_prompt_string(int promptmode)
1627{
1628 const char *prompt_str;
1629 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001630 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1631 /* Set up the prompt */
1632 if (promptmode == 0) { /* PS1 */
1633 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001634 /* bash uses $PWD value, even if it is set by user.
1635 * It uses current dir only if PWD is unset.
1636 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001637 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001638 prompt_str = G.PS1;
1639 } else
1640 prompt_str = G.PS2;
1641 } else
1642 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001643 debug_printf("result '%s'\n", prompt_str);
1644 return prompt_str;
1645}
1646
1647static void get_user_input(struct in_str *i)
1648{
1649 int r;
1650 const char *prompt_str;
1651
1652 prompt_str = setup_prompt_string(i->promptmode);
1653#if ENABLE_FEATURE_EDITING
1654 /* Enable command line editing only while a command line
1655 * is actually being read */
1656 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001657 G.flag_SIGINT = 0;
1658 /* buglet: SIGINT will not make new prompt to appear _at once_,
1659 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001660 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 +00001661 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001662 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001663 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001664 i->eof_flag = (r < 0);
1665 if (i->eof_flag) { /* EOF/error detected */
1666 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1667 G.user_input_buf[1] = '\0';
1668 }
1669#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001670 do {
1671 G.flag_SIGINT = 0;
1672 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001673 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001674 G.user_input_buf[0] = r = fgetc(i->file);
1675 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001676//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001677 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001678 i->eof_flag = (r == EOF);
1679#endif
1680 i->p = G.user_input_buf;
1681}
1682
1683#endif /* INTERACTIVE */
1684
1685/* This is the magic location that prints prompts
1686 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001687static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001688{
1689 int ch;
1690
1691 /* If there is data waiting, eat it up */
1692 if (i->p && *i->p) {
1693#if ENABLE_HUSH_INTERACTIVE
1694 take_cached:
1695#endif
1696 ch = *i->p++;
1697 if (i->eof_flag && !*i->p)
1698 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001699 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001700 } else {
1701 /* need to double check i->file because we might be doing something
1702 * more complicated by now, like sourcing or substituting. */
1703#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001704 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001705 do {
1706 get_user_input(i);
1707 } while (!*i->p); /* need non-empty line */
1708 i->promptmode = 1; /* PS2 */
1709 i->promptme = 0;
1710 goto take_cached;
1711 }
1712#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001713 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001714 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001715 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001716#if ENABLE_HUSH_INTERACTIVE
1717 if (ch == '\n')
1718 i->promptme = 1;
1719#endif
1720 return ch;
1721}
1722
Denis Vlasenko913a2012009-04-05 22:17:04 +00001723/* All callers guarantee this routine will never
1724 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001725 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001726static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001727{
1728 int ch;
1729 if (i->p && *i->p) {
1730 if (i->eof_flag && !i->p[1])
1731 return EOF;
1732 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001733 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001734 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001735 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001736 i->eof_flag = (ch == EOF);
1737 i->peek_buf[0] = ch;
1738 i->peek_buf[1] = '\0';
1739 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001740 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001741 return ch;
1742}
1743
1744static void setup_file_in_str(struct in_str *i, FILE *f)
1745{
1746 i->peek = file_peek;
1747 i->get = file_get;
1748#if ENABLE_HUSH_INTERACTIVE
1749 i->promptme = 1;
1750 i->promptmode = 0; /* PS1 */
1751#endif
1752 i->file = f;
1753 i->p = NULL;
1754}
1755
1756static void setup_string_in_str(struct in_str *i, const char *s)
1757{
1758 i->peek = static_peek;
1759 i->get = static_get;
1760#if ENABLE_HUSH_INTERACTIVE
1761 i->promptme = 1;
1762 i->promptmode = 0; /* PS1 */
1763#endif
1764 i->p = s;
1765 i->eof_flag = 0;
1766}
1767
1768
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001769/*
1770 * o_string support
1771 */
1772#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001773
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001774static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001775{
1776 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001777 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001778 if (o->data)
1779 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001780}
1781
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001782static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001783{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001784 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001785 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001786}
1787
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001788static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1789{
1790 free(o->data);
1791}
1792
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001793static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001794{
1795 if (o->length + len > o->maxlen) {
1796 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1797 o->data = xrealloc(o->data, 1 + o->maxlen);
1798 }
1799}
1800
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001801static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001802{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001803 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1804 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001805 o->data[o->length] = ch;
1806 o->length++;
1807 o->data[o->length] = '\0';
1808}
1809
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001810static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001811{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001812 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001813 memcpy(&o->data[o->length], str, len);
1814 o->length += len;
1815 o->data[o->length] = '\0';
1816}
1817
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001818#if !BB_MMU
1819static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001820{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001821 o_addblock(o, str, strlen(str));
1822}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001823static void nommu_addchr(o_string *o, int ch)
1824{
1825 if (o)
1826 o_addchr(o, ch);
1827}
1828#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001829# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001830#endif
1831
1832static void o_addstr_with_NUL(o_string *o, const char *str)
1833{
1834 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001835}
1836
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001837static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001838{
1839 while (len) {
1840 o_addchr(o, *str);
1841 if (*str++ == '\\'
1842 && (*str != '*' && *str != '?' && *str != '[')
1843 ) {
1844 o_addchr(o, '\\');
1845 }
1846 len--;
1847 }
1848}
1849
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001850#undef HUSH_BRACE_EXP
1851/*
1852 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
1853 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
1854 * Apparently, on unquoted $v bash still does globbing
1855 * ("v='*.txt'; echo $v" prints all .txt files),
1856 * but NOT brace expansion! Thus, there should be TWO independent
1857 * quoting mechanisms on $v expansion side: one protects
1858 * $v from brace expansion, and other additionally protects "$v" against globbing.
1859 * We have only second one.
1860 */
1861
1862#ifdef HUSH_BRACE_EXP
1863# define MAYBE_BRACES "{}"
1864#else
1865# define MAYBE_BRACES ""
1866#endif
1867
Eric Andersen25f27032001-04-26 23:22:31 +00001868/* My analysis of quoting semantics tells me that state information
1869 * is associated with a destination, not a source.
1870 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001871static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001872{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001873 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001874 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001875 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001876 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001877 o_grow_by(o, sz);
1878 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001879 o->data[o->length] = '\\';
1880 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001881 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001882 o->data[o->length] = ch;
1883 o->length++;
1884 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001885}
1886
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001887static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001888{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001889 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001890 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001891 sz++;
1892 o->data[o->length] = '\\';
1893 o->length++;
1894 }
1895 o_grow_by(o, sz);
1896 o->data[o->length] = ch;
1897 o->length++;
1898 o->data[o->length] = '\0';
1899}
1900
1901static void o_addQstr(o_string *o, const char *str, int len)
1902{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001903 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001904 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001905 return;
1906 }
1907 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001908 char ch;
1909 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001910 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001911 if (ordinary_cnt > len) /* paranoia */
1912 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001913 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001914 if (ordinary_cnt == len)
1915 return;
1916 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001917 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001918
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001919 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001920 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001921 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001922 sz++;
1923 o->data[o->length] = '\\';
1924 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001925 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001926 o_grow_by(o, sz);
1927 o->data[o->length] = ch;
1928 o->length++;
1929 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001930 }
1931}
1932
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001933/* A special kind of o_string for $VAR and `cmd` expansion.
1934 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001935 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001936 * list[i] contains an INDEX (int!) into this string data.
1937 * It means that if list[] needs to grow, data needs to be moved higher up
1938 * but list[i]'s need not be modified.
1939 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001940 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001941 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1942 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001943#if DEBUG_EXPAND || DEBUG_GLOB
1944static void debug_print_list(const char *prefix, o_string *o, int n)
1945{
1946 char **list = (char**)o->data;
1947 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1948 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001949
1950 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001951 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1952 prefix, list, n, string_start, o->length, o->maxlen);
1953 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001954 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001955 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1956 o->data + (int)list[i] + string_start,
1957 o->data + (int)list[i] + string_start);
1958 i++;
1959 }
1960 if (n) {
1961 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001962 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001963 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001964 }
1965}
1966#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001967# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001968#endif
1969
1970/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1971 * in list[n] so that it points past last stored byte so far.
1972 * It returns n+1. */
1973static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001974{
1975 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001976 int string_start;
1977 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001978
1979 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001980 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1981 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001982 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001983 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001984 /* list[n] points to string_start, make space for 16 more pointers */
1985 o->maxlen += 0x10 * sizeof(list[0]);
1986 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001987 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001988 memmove(list + n + 0x10, list + n, string_len);
1989 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001990 } else {
1991 debug_printf_list("list[%d]=%d string_start=%d\n",
1992 n, string_len, string_start);
1993 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001994 } else {
1995 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001996 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1997 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001998 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1999 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002000 o->has_empty_slot = 0;
2001 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002002 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002003 return n + 1;
2004}
2005
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002006/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002007static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002008{
2009 char **list = (char**)o->data;
2010 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2011
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002012 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002013}
2014
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002015#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002016/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2017 * first, it processes even {a} (no commas), second,
2018 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002019 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002020 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002021
2022/* Helper */
2023static int glob_needed(const char *s)
2024{
2025 while (*s) {
2026 if (*s == '\\') {
2027 if (!s[1])
2028 return 0;
2029 s += 2;
2030 continue;
2031 }
2032 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2033 return 1;
2034 s++;
2035 }
2036 return 0;
2037}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002038/* Return pointer to next closing brace or to comma */
2039static const char *next_brace_sub(const char *cp)
2040{
2041 unsigned depth = 0;
2042 cp++;
2043 while (*cp != '\0') {
2044 if (*cp == '\\') {
2045 if (*++cp == '\0')
2046 break;
2047 cp++;
2048 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002049 }
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002050 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2051 break;
2052 if (*cp++ == '{') /*}*/
2053 depth++;
2054 }
2055
2056 return *cp != '\0' ? cp : NULL;
2057}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002058/* Recursive brace globber. Note: may garble pattern[]. */
2059static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002060{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002061 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002062 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002063 const char *next;
2064 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002065 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002066 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002067
2068 debug_printf_glob("glob_brace('%s')\n", pattern);
2069
2070 begin = pattern;
2071 while (1) {
2072 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002073 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002074 if (*begin == '{') /*}*/ {
2075 /* Find the first sub-pattern and at the same time
2076 * find the rest after the closing brace */
2077 next = next_brace_sub(begin);
2078 if (next == NULL) {
2079 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002080 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002081 }
2082 /*{*/ if (*next == '}') {
2083 /* "{abc}" with no commas - illegal
2084 * brace expr, disregard and skip it */
2085 begin = next + 1;
2086 continue;
2087 }
2088 break;
2089 }
2090 if (*begin == '\\' && begin[1] != '\0')
2091 begin++;
2092 begin++;
2093 }
2094 debug_printf_glob("begin:%s\n", begin);
2095 debug_printf_glob("next:%s\n", next);
2096
2097 /* Now find the end of the whole brace expression */
2098 rest = next;
2099 /*{*/ while (*rest != '}') {
2100 rest = next_brace_sub(rest);
2101 if (rest == NULL) {
2102 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002103 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002104 }
2105 debug_printf_glob("rest:%s\n", rest);
2106 }
2107 rest_len = strlen(++rest) + 1;
2108
2109 /* We are sure the brace expression is well-formed */
2110
2111 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002112 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002113
2114 /* We have a brace expression. BEGIN points to the opening {,
2115 * NEXT points past the terminator of the first element, and REST
2116 * points past the final }. We will accumulate result names from
2117 * recursive runs for each brace alternative in the buffer using
2118 * GLOB_APPEND. */
2119
2120 p = begin + 1;
2121 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002122 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002123 memcpy(
2124 mempcpy(
2125 mempcpy(new_pattern_buf,
2126 /* We know the prefix for all sub-patterns */
2127 pattern, begin - pattern),
2128 p, next - p),
2129 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002130
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002131 /* Note: glob_brace() may garble new_pattern_buf[].
2132 * That's why we re-copy prefix every time (1st memcpy above).
2133 */
2134 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002135 /*{*/ if (*next == '}') {
2136 /* We saw the last entry */
2137 break;
2138 }
2139 p = next + 1;
2140 next = next_brace_sub(next);
2141 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002142 free(new_pattern_buf);
2143 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002144
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002145 simple_glob:
2146 {
2147 int gr;
2148 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002149
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002150 memset(&globdata, 0, sizeof(globdata));
2151 gr = glob(pattern, 0, NULL, &globdata);
2152 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2153 if (gr != 0) {
2154 if (gr == GLOB_NOMATCH) {
2155 globfree(&globdata);
2156 /* NB: garbles parameter */
2157 unbackslash(pattern);
2158 o_addstr_with_NUL(o, pattern);
2159 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2160 return o_save_ptr_helper(o, n);
2161 }
2162 if (gr == GLOB_NOSPACE)
2163 bb_error_msg_and_die(bb_msg_memory_exhausted);
2164 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2165 * but we didn't specify it. Paranoia again. */
2166 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2167 }
2168 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2169 char **argv = globdata.gl_pathv;
2170 while (1) {
2171 o_addstr_with_NUL(o, *argv);
2172 n = o_save_ptr_helper(o, n);
2173 argv++;
2174 if (!*argv)
2175 break;
2176 }
2177 }
2178 globfree(&globdata);
2179 }
2180 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002181}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002182/* Performs globbing on last list[],
2183 * saving each result as a new list[].
2184 */
2185static int o_glob(o_string *o, int n)
2186{
2187 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002188
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002189 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2190 if (!o->data)
2191 return o_save_ptr_helper(o, n);
2192 pattern = o->data + o_get_last_ptr(o, n);
2193 debug_printf_glob("glob pattern '%s'\n", pattern);
2194 if (!glob_needed(pattern)) {
2195 /* unbackslash last string in o in place, fix length */
2196 o->length = unbackslash(pattern) - o->data;
2197 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2198 return o_save_ptr_helper(o, n);
2199 }
2200
2201 copy = xstrdup(pattern);
2202 /* "forget" pattern in o */
2203 o->length = pattern - o->data;
2204 n = glob_brace(copy, o, n);
2205 free(copy);
2206 if (DEBUG_GLOB)
2207 debug_print_list("o_glob returning", o, n);
2208 return n;
2209}
2210
2211#else
2212
2213/* Helper */
2214static int glob_needed(const char *s)
2215{
2216 while (*s) {
2217 if (*s == '\\') {
2218 if (!s[1])
2219 return 0;
2220 s += 2;
2221 continue;
2222 }
2223 if (*s == '*' || *s == '[' || *s == '?')
2224 return 1;
2225 s++;
2226 }
2227 return 0;
2228}
2229/* Performs globbing on last list[],
2230 * saving each result as a new list[].
2231 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002232static int o_glob(o_string *o, int n)
2233{
2234 glob_t globdata;
2235 int gr;
2236 char *pattern;
2237
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002238 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002239 if (!o->data)
2240 return o_save_ptr_helper(o, n);
2241 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002242 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002243 if (!glob_needed(pattern)) {
2244 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002245 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002246 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002247 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002248 return o_save_ptr_helper(o, n);
2249 }
2250
2251 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002252 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2253 * If we glob "*.\*" and don't find anything, we need
2254 * to fall back to using literal "*.*", but GLOB_NOCHECK
2255 * will return "*.\*"!
2256 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002257 gr = glob(pattern, 0, NULL, &globdata);
2258 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002259 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002260 if (gr == GLOB_NOMATCH) {
2261 globfree(&globdata);
2262 goto literal;
2263 }
2264 if (gr == GLOB_NOSPACE)
2265 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002266 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2267 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002268 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002269 }
2270 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2271 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002272 /* "forget" pattern in o */
2273 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002274 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002275 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002276 n = o_save_ptr_helper(o, n);
2277 argv++;
2278 if (!*argv)
2279 break;
2280 }
2281 }
2282 globfree(&globdata);
2283 if (DEBUG_GLOB)
2284 debug_print_list("o_glob returning", o, n);
2285 return n;
2286}
2287
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002288#endif
2289
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002290/* If o->o_glob == 1, glob the string so far remembered.
2291 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002292static int o_save_ptr(o_string *o, int n)
2293{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002294 if (o->o_glob) { /* if globbing is requested */
2295 /* If o->has_empty_slot, list[n] was already globbed
2296 * (if it was requested back then when it was filled)
2297 * so don't do that again! */
2298 if (!o->has_empty_slot)
2299 return o_glob(o, n); /* o_save_ptr_helper is inside */
2300 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002301 return o_save_ptr_helper(o, n);
2302}
2303
2304/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002305static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002306{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002307 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002308 int string_start;
2309
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002310 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2311 if (DEBUG_EXPAND)
2312 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002313 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002314 list = (char**)o->data;
2315 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2316 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002317 while (n) {
2318 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002319 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002320 }
2321 return list;
2322}
2323
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002324
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002325/* Expansion can recurse */
2326#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002327static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002328#endif
2329static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002330#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002331#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002332 parse_stream_dquoted(dest, input, dquote_end)
2333#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002334static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002335 o_string *dest,
2336 struct in_str *input,
2337 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002338
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002339/* expand_strvec_to_strvec() takes a list of strings, expands
2340 * all variable references within and returns a pointer to
2341 * a list of expanded strings, possibly with larger number
2342 * of strings. (Think VAR="a b"; echo $VAR).
2343 * This new list is allocated as a single malloc block.
2344 * NULL-terminated list of char* pointers is at the beginning of it,
2345 * followed by strings themself.
2346 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002347
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002348/* Store given string, finalizing the word and starting new one whenever
2349 * we encounter IFS char(s). This is used for expanding variable values.
2350 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2351static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002352{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002353 while (1) {
2354 int word_len = strcspn(str, G.ifs);
2355 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002356 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002357 o_addQstr(output, str, word_len);
2358 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002359 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002360 str += word_len;
2361 }
2362 if (!*str) /* EOL - do not finalize word */
2363 break;
2364 o_addchr(output, '\0');
2365 debug_print_list("expand_on_ifs", output, n);
2366 n = o_save_ptr(output, n);
2367 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002368 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002369 debug_print_list("expand_on_ifs[1]", output, n);
2370 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002371}
2372
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002373/* Helper to expand $((...)) and heredoc body. These act as if
2374 * they are in double quotes, with the exception that they are not :).
2375 * Just the rules are similar: "expand only $var and `cmd`"
2376 *
2377 * Returns malloced string.
2378 * As an optimization, we return NULL if expansion is not needed.
2379 */
2380static char *expand_pseudo_dquoted(const char *str)
2381{
2382 char *exp_str;
2383 struct in_str input;
2384 o_string dest = NULL_O_STRING;
2385
2386 if (strchr(str, '$') == NULL
2387#if ENABLE_HUSH_TICK
2388 && strchr(str, '`') == NULL
2389#endif
2390 ) {
2391 return NULL;
2392 }
2393
2394 /* We need to expand. Example:
2395 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2396 */
2397 setup_string_in_str(&input, str);
2398 parse_stream_dquoted(NULL, &dest, &input, EOF);
2399 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2400 exp_str = expand_string_to_string(dest.data);
2401 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2402 o_free_unsafe(&dest);
2403 return exp_str;
2404}
2405
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002406/* Expand all variable references in given string, adding words to list[]
2407 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2408 * to be filled). This routine is extremely tricky: has to deal with
2409 * variables/parameters with whitespace, $* and $@, and constructs like
2410 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02002411static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002412{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002413 /* or_mask is either 0 (normal case) or 0x80 -
2414 * expansion of right-hand side of assignment == 1-element expand.
2415 * It will also do no globbing, and thus we must not backslash-quote!
2416 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002417 char ored_ch;
2418 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002419
2420 ored_ch = 0;
2421
Denys Vlasenkof37eb392009-10-18 11:46:35 +02002422 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002423 debug_print_list("expand_vars_to_list", output, n);
2424 n = o_save_ptr(output, n);
2425 debug_print_list("expand_vars_to_list[0]", output, n);
2426
2427 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002428 char first_ch;
2429 int i;
2430 char *dyn_val = NULL;
2431 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002432#if ENABLE_HUSH_TICK
2433 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002434#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002435#if ENABLE_SH_MATH_SUPPORT
2436 char arith_buf[sizeof(arith_t)*3 + 2];
2437#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002438 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002439 debug_print_list("expand_vars_to_list[1]", output, n);
2440 arg = ++p;
2441 p = strchr(p, SPECIAL_VAR_SYMBOL);
2442
2443 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2444 /* "$@" is special. Even if quoted, it can still
2445 * expand to nothing (not even an empty string) */
2446 if ((first_ch & 0x7f) != '@')
2447 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002448
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002449 switch (first_ch & 0x7f) {
2450 /* Highest bit in first_ch indicates that var is double-quoted */
2451 case '$': /* pid */
2452 val = utoa(G.root_pid);
2453 break;
2454 case '!': /* bg pid */
2455 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2456 break;
2457 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002458 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002459 break;
2460 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002461 if (arg[1] != SPECIAL_VAR_SYMBOL)
2462 /* actually, it's a ${#var} */
2463 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002464 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2465 break;
2466 case '*':
2467 case '@':
2468 i = 1;
2469 if (!G.global_argv[i])
2470 break;
2471 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2472 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002473 smallint sv = output->o_escape;
2474 /* unquoted var's contents should be globbed, so don't escape */
2475 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002476 while (G.global_argv[i]) {
2477 n = expand_on_ifs(output, n, G.global_argv[i]);
2478 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2479 if (G.global_argv[i++][0] && G.global_argv[i]) {
2480 /* this argv[] is not empty and not last:
2481 * put terminating NUL, start new word */
2482 o_addchr(output, '\0');
2483 debug_print_list("expand_vars_to_list[2]", output, n);
2484 n = o_save_ptr(output, n);
2485 debug_print_list("expand_vars_to_list[3]", output, n);
2486 }
2487 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002488 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002489 } else
2490 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2491 * and in this case should treat it like '$*' - see 'else...' below */
2492 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2493 while (1) {
2494 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2495 if (++i >= G.global_argc)
2496 break;
2497 o_addchr(output, '\0');
2498 debug_print_list("expand_vars_to_list[4]", output, n);
2499 n = o_save_ptr(output, n);
2500 }
2501 } else { /* quoted $*: add as one word */
2502 while (1) {
2503 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2504 if (!G.global_argv[++i])
2505 break;
2506 if (G.ifs[0])
2507 o_addchr(output, G.ifs[0]);
2508 }
2509 }
2510 break;
2511 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2512 /* "Empty variable", used to make "" etc to not disappear */
2513 arg++;
2514 ored_ch = 0x80;
2515 break;
2516#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002517 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002518 *p = '\0';
2519 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002520 /* Can't just stuff it into output o_string,
2521 * expanded result may need to be globbed
2522 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002523 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko647553a2009-11-15 19:58:19 +01002524 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenkocddbb612010-05-20 14:27:09 +02002525 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002526 val = subst_result.data;
2527 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002528#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002529#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002530 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002531 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002532 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002533 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002534 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002535
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002536 arg++; /* skip '+' */
2537 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002538 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002539
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002540 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002541 hooks.lookupvar = get_local_var_value;
Denys Vlasenko03dad222010-01-12 23:29:57 +01002542 hooks.setvar = set_local_var_from_halves;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002543 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002544 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2545 free(exp_str);
2546
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002547 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002548 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002549 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002550 case -3:
2551 msg = "exponent less than 0";
2552 break;
2553 case -2:
2554 msg = "divide by 0";
2555 break;
2556 case -5:
2557 msg = "expression recursion loop detected";
2558 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002559 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002560 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002561 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002562 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002563 sprintf(arith_buf, arith_t_fmt, res);
2564 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002565 break;
2566 }
2567#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002568 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002569 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002570 char *var = arg;
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002571 char exp_len; /* '#' if it's ${#var} */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002572 char exp_op;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002573 char exp_save = exp_save; /* for compiler */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002574 char *exp_saveptr = exp_saveptr; /* points to expansion operator */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002575 char *exp_word = exp_word; /* for compiler */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002576
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002577 *p = '\0';
2578 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002579
2580 /* prepare for expansions */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002581 exp_op = 0;
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002582 exp_len = var[0];
2583 if (exp_len == '#') {
Mike Frysinger6379bb42009-03-28 18:55:03 +00002584 /* handle length expansion ${#var} */
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002585 var++;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002586 } else {
2587 /* maybe handle parameter expansion */
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002588 exp_saveptr = var + strcspn(var, "%#:-=+?");
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002589 exp_save = *exp_saveptr;
2590 if (exp_save) {
2591 exp_word = exp_saveptr;
2592 if (exp_save == ':')
2593 exp_word++;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002594 exp_op = *exp_word++;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002595 *exp_saveptr = '\0';
Mike Frysinger6379bb42009-03-28 18:55:03 +00002596 }
2597 }
2598
2599 /* lookup the variable in question */
2600 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002601 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002602 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002603 if (i < G.global_argc)
2604 val = G.global_argv[i];
2605 /* else val remains NULL: $N with too big N */
2606 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002607 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002608
2609 /* handle any expansions */
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002610 if (exp_len == '#') {
2611 debug_printf_expand("expand: length(%s)=", val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002612 val = utoa(val ? strlen(val) : 0);
2613 debug_printf_expand("%s\n", val);
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002614 } else if (exp_op) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002615 if (exp_op == '%' || exp_op == '#') {
Denys Vlasenko53b51332010-05-20 21:46:45 +02002616 /* Standard-mandated substring removal ops:
2617 * ${parameter%word} - remove smallest suffix pattern
2618 * ${parameter%%word} - remove largest suffix pattern
2619 * ${parameter#word} - remove smallest prefix pattern
2620 * ${parameter##word} - remove largest prefix pattern
2621 *
2622 * Word is expanded to produce a glob pattern.
2623 * Then var's value is matched to it and matching part removed.
2624 */
Mike Frysinger57e74672009-04-09 23:00:33 +00002625 if (val) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002626 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002627 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002628 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002629 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002630 exp_word++;
Mike Frysinger57e74672009-04-09 23:00:33 +00002631 val = dyn_val = xstrdup(val);
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002632 loc = scan(dyn_val, exp_word, match_at_left);
2633 if (match_at_left) /* # or ## */
Mike Frysinger57e74672009-04-09 23:00:33 +00002634 val = loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002635 else if (loc) /* % or %% and match was found */
Mike Frysinger57e74672009-04-09 23:00:33 +00002636 *loc = '\0';
2637 }
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002638 } else if (!strchr("%#:-=+?"+3, exp_op)) {
2639#if ENABLE_HUSH_BASH_COMPAT
2640 /* exp_op is ':' and next char isn't a subst operator.
2641 * Assuming it's ${var:[N][:M]} bashism.
2642 * TODO: N, M can be expressions similar to $((EXPR)): 2+2, 2+var etc
2643 */
2644 char *end;
2645 unsigned len = INT_MAX;
2646 unsigned beg = 0;
2647 end = --exp_word;
2648 if (*exp_word != ':') /* not ${var::...} */
2649 beg = bb_strtou(exp_word, &end, 0);
2650 //bb_error_msg("beg:'%s'=%u end:'%s'", exp_word, beg, end);
2651 if (*end == ':') {
2652 len = bb_strtou(end + 1, &end, 0);
2653 //bb_error_msg("len:%u end:'%s'", len, end);
2654 }
2655 if (*end == '\0'
2656 && end != exp_word /* not "${var:}" */
2657 ) {
2658 //bb_error_msg("from val:'%s'", val);
2659 if (!val || beg >= strlen(val))
2660 val = "";
2661 else
2662 val = dyn_val = xstrndup(val + beg, len);
2663 //bb_error_msg("val:'%s'", val);
2664 } else
2665#endif
2666 {
2667 die_if_script("malformed ${%s...}", var);
2668 }
2669 } else { /* one of "-=+?" */
Denys Vlasenko53b51332010-05-20 21:46:45 +02002670 /* Standard-mandated substitution ops:
2671 * ${var?word} - indicate error if unset
2672 * If var is unset, word (or a message indicating it is unset
2673 * if word is null) is written to standard error
2674 * and the shell exits with a non-zero exit status.
2675 * Otherwise, the value of var is substituted.
2676 * ${var-word} - use default value
2677 * If var is unset, word is substituted.
2678 * ${var=word} - assign and use default value
2679 * If var is unset, word is assigned to var.
2680 * In all cases, final value of var is substituted.
2681 * ${var+word} - use alternative value
2682 * If var is unset, null is substituted.
2683 * Otherwise, word is substituted.
2684 *
2685 * Word is subjected to tilde expansion, parameter expansion,
2686 * command substitution, and arithmetic expansion.
2687 * If word is not needed, it is not expanded.
2688 *
2689 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2690 * but also treat null var as if it is unset.
2691 */
2692 int use_word = (!val || ((exp_save == ':') && !val[0]));
Mike Frysingera4f331d2009-04-07 06:03:22 +00002693 if (exp_op == '+')
Denys Vlasenko53b51332010-05-20 21:46:45 +02002694 use_word = !use_word;
Mike Frysingera4f331d2009-04-07 06:03:22 +00002695 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
Denys Vlasenko53b51332010-05-20 21:46:45 +02002696 (exp_save == ':') ? "true" : "false", use_word);
2697 if (use_word) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002698 if (exp_op == '?') {
2699//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002700 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002701 die_if_script("%s: %s",
2702 var,
2703 exp_word[0] ? exp_word : "parameter null or not set"
2704 );
2705 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002706 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002707 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002708
Mike Frysingera4f331d2009-04-07 06:03:22 +00002709 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002710 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002711 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002712 /* mimic bash message */
2713 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002714 val = NULL;
2715 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002716 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002717 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002718 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002719 }
2720 }
2721 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002722
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002723 *exp_saveptr = exp_save;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002724 } /* if (exp_op) */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002725
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002726 arg[0] = first_ch;
2727#if ENABLE_HUSH_TICK
2728 store_val:
2729#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002730 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002731 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002732 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002733 /* unquoted var's contents should be globbed, so don't escape */
2734 smallint sv = output->o_escape;
2735 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002736 n = expand_on_ifs(output, n, val);
2737 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002738 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002739 }
2740 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002741 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002742 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002743 } /* default: */
2744 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002745
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002746 if (val) {
2747 o_addQstr(output, val, strlen(val));
2748 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002749 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002750 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002751 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002752 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002753
2754#if ENABLE_HUSH_TICK
2755 o_free(&subst_result);
2756#endif
2757 arg = ++p;
2758 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2759
2760 if (arg[0]) {
2761 debug_print_list("expand_vars_to_list[a]", output, n);
2762 /* this part is literal, and it was already pre-quoted
2763 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002764 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002765 debug_print_list("expand_vars_to_list[b]", output, n);
2766 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2767 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2768 ) {
2769 n--;
2770 /* allow to reuse list[n] later without re-growth */
2771 output->has_empty_slot = 1;
2772 } else {
2773 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002774 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002775 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002776}
2777
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002778static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002779{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002780 int n;
2781 char **list;
2782 char **v;
2783 o_string output = NULL_O_STRING;
2784
2785 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002786 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002787 /* (unquoted $var will temporarily switch it off) */
2788 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002789 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002790
2791 n = 0;
2792 v = argv;
2793 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002794 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002795 v++;
2796 }
2797 debug_print_list("expand_variables", &output, n);
2798
2799 /* output.data (malloced in one block) gets returned in "list" */
2800 list = o_finalize_list(&output, n);
2801 debug_print_strings("expand_variables[1]", list);
2802 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002803}
2804
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002805static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002806{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002807 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002808}
2809
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002810#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002811static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2812{
2813 return expand_variables(argv, 0x80);
2814}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002815#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002816
2817#ifdef CMD_SINGLEWORD_NOGLOB_COND
2818static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2819{
2820 int n;
2821 char **list;
2822 char **v;
2823 o_string output = NULL_O_STRING;
2824
2825 n = 0;
2826 v = argv;
2827 while (*v) {
2828 int is_var = is_well_formed_var_name(*v, '=');
2829 /* is_var * 0x80: singleword expansion for vars */
2830 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2831
2832 /* Subtle! expand_vars_to_list did not glob last word yet.
2833 * It does this only when fed with further data.
2834 * Therefore we set globbing flags AFTER it, not before:
2835 */
2836
2837 /* if it is not recognizably abc=...; then: */
2838 output.o_escape = !is_var; /* protect against globbing for "$var" */
2839 /* (unquoted $var will temporarily switch it off) */
2840 output.o_glob = !is_var; /* and indeed do globbing */
2841 v++;
2842 }
2843 debug_print_list("expand_cond", &output, n);
2844
2845 /* output.data (malloced in one block) gets returned in "list" */
2846 list = o_finalize_list(&output, n);
2847 debug_print_strings("expand_cond[1]", list);
2848 return list;
2849}
2850#endif
2851
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002852/* Used for expansion of right hand of assignments */
2853/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2854 * "v=/bin/c*" */
2855static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002856{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002857 char *argv[2], **list;
2858
2859 argv[0] = (char*)str;
2860 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002861 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002862 if (HUSH_DEBUG)
2863 if (!list[0] || list[1])
2864 bb_error_msg_and_die("BUG in varexp2");
2865 /* actually, just move string 2*sizeof(char*) bytes back */
2866 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002867 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002868 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2869 return (char*)list;
2870}
2871
2872/* Used for "eval" builtin */
2873static char* expand_strvec_to_string(char **argv)
2874{
2875 char **list;
2876
2877 list = expand_variables(argv, 0x80);
2878 /* Convert all NULs to spaces */
2879 if (list[0]) {
2880 int n = 1;
2881 while (list[n]) {
2882 if (HUSH_DEBUG)
2883 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2884 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002885 /* bash uses ' ' regardless of $IFS contents */
2886 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002887 n++;
2888 }
2889 }
2890 overlapping_strcpy((char*)list, list[0]);
2891 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2892 return (char*)list;
2893}
2894
2895static char **expand_assignments(char **argv, int count)
2896{
2897 int i;
2898 char **p = NULL;
2899 /* Expand assignments into one string each */
2900 for (i = 0; i < count; i++) {
2901 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2902 }
2903 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002904}
2905
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002906
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002907#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002908/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002909void re_execute_shell(char ***to_free, const char *s,
2910 char *g_argv0, char **g_argv,
2911 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002912
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002913static void reset_traps_to_defaults(void)
2914{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002915 /* This function is always called in a child shell
2916 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002917 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002918 unsigned sig;
2919 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002920
Denys Vlasenko67f71862009-09-25 14:21:06 +02002921 /* Child shells are not interactive.
2922 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2923 * Testcase: (while :; do :; done) + ^Z should background.
2924 * Same goes for SIGTERM, SIGHUP, SIGINT.
2925 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002926 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02002927 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002928
Denys Vlasenko67f71862009-09-25 14:21:06 +02002929 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2930 * Stupid. It can be done with *single* &= op, but we can't use
2931 * the fact that G.blocked_set is implemented as a bitmask
2932 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002933 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2934 sig = 1;
2935 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002936 if (mask & 1) {
2937 /* Careful. Only if no trap or trap is not "" */
2938 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2939 sigdelset(&G.blocked_set, sig);
2940 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002941 mask >>= 1;
2942 if (!mask)
2943 break;
2944 sig++;
2945 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02002946 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002947 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002948
2949 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002950 mask = G.non_DFL_mask;
2951 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002952 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002953 continue;
2954 free(G.traps[sig]);
2955 G.traps[sig] = NULL;
2956 /* There is no signal for 0 (EXIT) */
2957 if (sig == 0)
2958 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002959 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002960 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02002961 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002962 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002963 continue;
2964 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002965 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002966 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002967}
2968
2969#else /* !BB_MMU */
2970
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002971static void re_execute_shell(char ***to_free, const char *s,
2972 char *g_argv0, char **g_argv,
2973 char **builtin_argv) NORETURN;
2974static void re_execute_shell(char ***to_free, const char *s,
2975 char *g_argv0, char **g_argv,
2976 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002977{
Denys Vlasenko6c93b242010-01-12 19:28:10 +01002978#define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
2979 /* delims + 2 * (number of bytes in printed hex numbers) */
2980 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002981 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002982 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002983# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002984 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002985# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002986 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002987 unsigned cnt;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01002988 unsigned long long empty_trap_mask;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002989
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002990 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002991 argv = heredoc_argv;
2992 argv[0] = (char *) G.argv0_for_re_execing;
2993 argv[1] = (char *) "-<";
2994 argv[2] = (char *) s;
2995 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002996 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002997 goto do_exec;
2998 }
2999
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003000 cnt = 0;
3001 pp = builtin_argv;
3002 if (pp) while (*pp++)
3003 cnt++;
3004
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003005 empty_trap_mask = 0;
3006 if (G.traps) {
3007 int sig;
3008 for (sig = 1; sig < NSIG; sig++) {
3009 if (G.traps[sig] && !G.traps[sig][0])
3010 empty_trap_mask |= 1LL << sig;
3011 }
3012 }
3013
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003014 sprintf(param_buf, NOMMU_HACK_FMT
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003015 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02003016 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003017 , (unsigned) G.last_bg_pid
3018 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003019 , cnt
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003020 , empty_trap_mask
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003021 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003022 );
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003023#undef NOMMU_HACK_FMT
3024 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003025 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003026 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003027 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003028 for (cur = G.top_var; cur; cur = cur->next) {
3029 if (!cur->flg_export || cur->flg_read_only)
3030 cnt += 2;
3031 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003032# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003033 for (funcp = G.top_func; funcp; funcp = funcp->next)
3034 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003035# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003036 pp = g_argv;
3037 while (*pp++)
3038 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003039 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003040 *pp++ = (char *) G.argv0_for_re_execing;
3041 *pp++ = param_buf;
3042 for (cur = G.top_var; cur; cur = cur->next) {
3043 if (cur->varstr == hush_version_str)
3044 continue;
3045 if (cur->flg_read_only) {
3046 *pp++ = (char *) "-R";
3047 *pp++ = cur->varstr;
3048 } else if (!cur->flg_export) {
3049 *pp++ = (char *) "-V";
3050 *pp++ = cur->varstr;
3051 }
3052 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003053# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003054 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3055 *pp++ = (char *) "-F";
3056 *pp++ = funcp->name;
3057 *pp++ = funcp->body_as_string;
3058 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003059# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003060 /* We can pass activated traps here. Say, -Tnn:trap_string
3061 *
3062 * However, POSIX says that subshells reset signals with traps
3063 * to SIG_DFL.
3064 * I tested bash-3.2 and it not only does that with true subshells
3065 * of the form ( list ), but with any forked children shells.
3066 * I set trap "echo W" WINCH; and then tried:
3067 *
3068 * { echo 1; sleep 20; echo 2; } &
3069 * while true; do echo 1; sleep 20; echo 2; break; done &
3070 * true | { echo 1; sleep 20; echo 2; } | cat
3071 *
3072 * In all these cases sending SIGWINCH to the child shell
3073 * did not run the trap. If I add trap "echo V" WINCH;
3074 * _inside_ group (just before echo 1), it works.
3075 *
3076 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003077 * Even if we would use signal handlers instead of signal masking
3078 * in order to implement trap handling,
3079 * exec syscall below resets signals to SIG_DFL for us.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003080 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003081 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003082 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003083 if (builtin_argv) {
3084 while (*++builtin_argv)
3085 *pp++ = *builtin_argv;
3086 *pp++ = (char *) "";
3087 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003088 *pp++ = g_argv0;
3089 while (*g_argv)
3090 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003091 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003092 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003093
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003094 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003095 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3096 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003097 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003098 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003099 if (argv[0][0] == '/')
3100 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003101 xfunc_error_retval = 127;
3102 bb_error_msg_and_die("can't re-execute the shell");
3103}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003104#endif /* !BB_MMU */
3105
3106
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003107static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003108{
3109 struct fd_pair pair;
3110 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003111 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003112 /* the _body_ of heredoc (misleading field name) */
3113 const char *heredoc = redir->rd_filename;
3114 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003115#if !BB_MMU
3116 char **to_free;
3117#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003118
3119 expanded = NULL;
3120 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3121 expanded = expand_pseudo_dquoted(heredoc);
3122 if (expanded)
3123 heredoc = expanded;
3124 }
3125 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003126
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003127 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003128 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003129 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003130
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003131 /* Try writing without forking. Newer kernels have
3132 * dynamically growing pipes. Must use non-blocking write! */
3133 ndelay_on(pair.wr);
3134 while (1) {
3135 written = write(pair.wr, heredoc, len);
3136 if (written <= 0)
3137 break;
3138 len -= written;
3139 if (len == 0) {
3140 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00003141 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003142 return;
3143 }
3144 heredoc += written;
3145 }
3146 ndelay_off(pair.wr);
3147
3148 /* Okay, pipe buffer was not big enough */
3149 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003150 * for the unsuspecting parent process. Child creates a grandchild
3151 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003152 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003153#if !BB_MMU
3154 to_free = NULL;
3155#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003156 pid = vfork();
3157 if (pid < 0)
3158 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003159 if (pid == 0) {
3160 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003161 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003162 pid = BB_MMU ? fork() : vfork();
3163 if (pid < 0)
3164 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3165 if (pid != 0)
3166 _exit(0);
3167 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003168 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003169#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003170 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003171 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003172#else
3173 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003174 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003175 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003176#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003177 }
3178 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003179#if ENABLE_HUSH_FAST
3180 G.count_SIGCHLD++;
3181//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3182#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003183 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003184#if !BB_MMU
3185 free(to_free);
3186#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003187 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003188 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003189 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003190}
3191
Eric Andersen25f27032001-04-26 23:22:31 +00003192/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3193 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003194static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003195{
3196 int openfd, mode;
3197 struct redir_struct *redir;
3198
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003199 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003200 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003201 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003202 if (squirrel && redir->rd_fd < 3
3203 && squirrel[redir->rd_fd] < 0
3204 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003205 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003206 }
3207 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3208 * of the heredoc */
3209 debug_printf_parse("set heredoc '%s'\n",
3210 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003211 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003212 continue;
3213 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003214
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003215 if (redir->rd_dup == REDIRFD_TO_FILE) {
3216 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003217 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003218 if (redir->rd_filename == NULL) {
3219 /* Something went wrong in the parse.
3220 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003221 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003222 continue;
3223 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003224 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003225 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003226 openfd = open_or_warn(p, mode);
3227 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003228 if (openfd < 0) {
3229 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003230 * bash and ash both lose it as well (though zsh doesn't!) */
3231//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003232 return 1;
3233 }
3234 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003235 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003236 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003237 }
3238
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003239 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003240 if (squirrel && redir->rd_fd < 3
3241 && squirrel[redir->rd_fd] < 0
3242 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003243 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003244 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003245 if (openfd == REDIRFD_CLOSE) {
3246 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003247 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003248 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003249 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003250 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003251 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003252 }
Eric Andersen25f27032001-04-26 23:22:31 +00003253 }
3254 }
3255 return 0;
3256}
3257
3258static void restore_redirects(int squirrel[])
3259{
3260 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003261 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003262 fd = squirrel[i];
3263 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003264 /* We simply die on error */
3265 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003266 }
3267 }
3268}
3269
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003270
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003271static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003272
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003273/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003274static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003275{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003276 char **p;
3277 struct command *command;
3278 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003279 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003280
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003281 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003282 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003283 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003284 for (i = 0; i < pi->num_cmds; i++) {
3285 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003286 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003287 if (command->argv) {
3288 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003289 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003290 }
3291 free_strings(command->argv);
3292 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003293 }
3294 /* not "else if": on syntax error, we may have both! */
3295 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003296 debug_printf_clean(" begin group (cmd_type:%d)\n",
3297 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003298 free_pipe_list(command->group);
3299 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003300 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003301 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003302 /* else is crucial here.
3303 * If group != NULL, child_func is meaningless */
3304#if ENABLE_HUSH_FUNCTIONS
3305 else if (command->child_func) {
3306 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3307 command->child_func->parent_cmd = NULL;
3308 }
3309#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003310#if !BB_MMU
3311 free(command->group_as_string);
3312 command->group_as_string = NULL;
3313#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003314 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003315 debug_printf_clean(" redirect %d%s",
3316 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003317 /* guard against the case >$FOO, where foo is unset or blank */
3318 if (r->rd_filename) {
3319 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3320 free(r->rd_filename);
3321 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003322 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003323 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003324 rnext = r->next;
3325 free(r);
3326 }
3327 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003328 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003329 free(pi->cmds); /* children are an array, they get freed all at once */
3330 pi->cmds = NULL;
3331#if ENABLE_HUSH_JOB
3332 free(pi->cmdtext);
3333 pi->cmdtext = NULL;
3334#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003335}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003336
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003337static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003338{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003339 struct pipe *pi, *next;
3340
3341 for (pi = head; pi; pi = next) {
3342#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003343 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003344#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003345 free_pipe(pi);
3346 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003347 next = pi->next;
3348 /*pi->next = NULL;*/
3349 free(pi);
3350 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003351}
3352
3353
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003354static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003355#if BB_MMU
3356#define parse_stream(pstring, input, end_trigger) \
3357 parse_stream(input, end_trigger)
3358#endif
3359static struct pipe *parse_stream(char **pstring,
3360 struct in_str *input,
3361 int end_trigger);
3362static void parse_and_run_string(const char *s);
3363
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003364
Mike Frysinger93cadc22009-05-27 17:06:25 -04003365static char *find_in_path(const char *arg)
3366{
3367 char *ret = NULL;
3368 const char *PATH = get_local_var_value("PATH");
3369
3370 if (!PATH)
3371 return NULL;
3372
3373 while (1) {
3374 const char *end = strchrnul(PATH, ':');
3375 int sz = end - PATH; /* must be int! */
3376
3377 free(ret);
3378 if (sz != 0) {
3379 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3380 } else {
3381 /* We have xxx::yyyy in $PATH,
3382 * it means "use current dir" */
3383 ret = xstrdup(arg);
3384 }
3385 if (access(ret, F_OK) == 0)
3386 break;
3387
3388 if (*end == '\0') {
3389 free(ret);
3390 return NULL;
3391 }
3392 PATH = end + 1;
3393 }
3394
3395 return ret;
3396}
3397
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003398static const struct built_in_command* find_builtin_helper(const char *name,
3399 const struct built_in_command *x,
3400 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003401{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003402 while (x != end) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01003403 if (strcmp(name, x->b_cmd) != 0) {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003404 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003405 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003406 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003407 debug_printf_exec("found builtin '%s'\n", name);
3408 return x;
3409 }
3410 return NULL;
3411}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003412static const struct built_in_command* find_builtin1(const char *name)
3413{
3414 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3415}
3416static const struct built_in_command* find_builtin(const char *name)
3417{
3418 const struct built_in_command *x = find_builtin1(name);
3419 if (x)
3420 return x;
3421 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3422}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003423
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003424#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003425static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003426{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003427 struct function **funcpp = &G.top_func;
3428 while (*funcpp) {
3429 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003430 break;
3431 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003432 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003433 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003434 return funcpp;
3435}
3436
3437static const struct function *find_function(const char *name)
3438{
3439 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003440 if (funcp)
3441 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003442 return funcp;
3443}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003444
Denis Vlasenkobc569742009-04-12 20:35:19 +00003445/* Note: takes ownership on name ptr */
3446static struct function *new_function(char *name)
3447{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003448 struct function **funcpp = find_function_slot(name);
3449 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003450
Denys Vlasenko873273d2009-09-12 14:47:41 +02003451 if (funcp != NULL) {
3452 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003453 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3454 if (!cmd) {
3455 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3456 free(funcp->name);
3457 /* Note: if !funcp->body, do not free body_as_string!
3458 * This is a special case of "-F name body" function:
3459 * body_as_string was not malloced! */
3460 if (funcp->body) {
3461 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003462# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003463 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003464# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003465 }
3466 } else {
3467 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3468 cmd->argv[0] = funcp->name;
3469 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003470# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003471 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003472# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003473 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003474 } else {
3475 debug_printf_exec("remembering new function '%s'\n", name);
3476 funcp = *funcpp = xzalloc(sizeof(*funcp));
3477 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003478 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003479
Denis Vlasenkobc569742009-04-12 20:35:19 +00003480 funcp->name = name;
3481 return funcp;
3482}
3483
Denis Vlasenko40e84372009-04-18 11:23:38 +00003484static void unset_func(const char *name)
3485{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003486 struct function **funcpp = find_function_slot(name);
3487 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003488
Denys Vlasenko873273d2009-09-12 14:47:41 +02003489 if (funcp != NULL) {
3490 debug_printf_exec("freeing function '%s'\n", funcp->name);
3491 *funcpp = funcp->next;
3492 /* funcp is unlinked now, deleting it.
3493 * Note: if !funcp->body, the function was created by
3494 * "-F name body", do not free ->body_as_string
3495 * and ->name as they were not malloced. */
3496 if (funcp->body) {
3497 free_pipe_list(funcp->body);
3498 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003499# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003500 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003501# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003502 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003503 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003504 }
3505}
3506
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003507# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003508#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003509 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003510# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003511static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003512 const struct function *funcp,
3513 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003514static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003515 const struct function *funcp,
3516 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003517{
3518# if BB_MMU
3519 int n = 1;
3520
3521 argv[0] = G.global_argv[0];
3522 G.global_argv = argv;
3523 while (*++argv)
3524 n++;
3525 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003526 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003527 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003528 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003529 _exit(n);
3530# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003531 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003532 funcp->body_as_string,
3533 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003534 argv + 1,
3535 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003536# endif
3537}
3538
3539static int run_function(const struct function *funcp, char **argv)
3540{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003541 int rc;
3542 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003543 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003544
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003545 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003546
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003547 /* "we are in function, ok to use return" */
3548 sv_flg = G.flag_return_in_progress;
3549 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003550# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003551 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003552# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003553
Denis Vlasenkobc569742009-04-12 20:35:19 +00003554 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003555# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003556 if (!funcp->body) {
3557 /* Function defined by -F */
3558 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003559 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003560 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003561# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003562 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003563 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003564 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003565
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003566# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003567 {
3568 struct variable *var;
3569 struct variable **var_pp;
3570
3571 var_pp = &G.top_var;
3572 while ((var = *var_pp) != NULL) {
3573 if (var->func_nest_level < G.func_nest_level) {
3574 var_pp = &var->next;
3575 continue;
3576 }
3577 /* Unexport */
3578 if (var->flg_export)
3579 bb_unsetenv(var->varstr);
3580 /* Remove from global list */
3581 *var_pp = var->next;
3582 /* Free */
3583 if (!var->max_len)
3584 free(var->varstr);
3585 free(var);
3586 }
3587 G.func_nest_level--;
3588 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003589# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003590 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003591
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003592 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003593
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003594 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003595}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003596#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003597
3598
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003599#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003600#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003601 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003602#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003603#define exec_builtin(to_free, x, argv) \
3604 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003605#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003606static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003607 const struct built_in_command *x,
3608 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003609static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003610 const struct built_in_command *x,
3611 char **argv)
3612{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003613#if BB_MMU
Denys Vlasenko17323a62010-01-28 01:57:05 +01003614 int rcode = x->b_function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003615 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003616 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003617#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003618 /* On NOMMU, we must never block!
3619 * Example: { sleep 99 | read line; } & echo Ok
3620 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003621 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003622 argv[0],
3623 G.global_argv[0],
3624 G.global_argv + 1,
3625 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003626#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003627}
3628
3629
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003630static void execvp_or_die(char **argv) NORETURN;
3631static void execvp_or_die(char **argv)
3632{
3633 debug_printf_exec("execing '%s'\n", argv[0]);
3634 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3635 execvp(argv[0], argv);
3636 bb_perror_msg("can't execute '%s'", argv[0]);
3637 _exit(127); /* bash compat */
3638}
3639
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003640#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003641#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3642 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3643#define pseudo_exec(nommu_save, command, argv_expanded) \
3644 pseudo_exec(command, argv_expanded)
3645#endif
3646
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003647/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003648 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003649 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003650 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003651 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003652static void pseudo_exec_argv(nommu_save_t *nommu_save,
3653 char **argv, int assignment_cnt,
3654 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003655static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003656 char **argv, int assignment_cnt,
3657 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003658{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003659 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003660
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003661 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003662 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003663 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003664
Denis Vlasenko9504e442008-10-29 01:19:15 +00003665 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003666#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003667 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003668 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003669 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003670 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003671#else
3672 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003673 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003674#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003675 if (argv_expanded) {
3676 argv = argv_expanded;
3677 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003678 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003679#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003680 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003681#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003682 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003683
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003684#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3685 if (strchr(argv[0], '/') != NULL)
3686 goto skip;
3687#endif
3688
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003689 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003690 * Depending on context, this might be redundant. But it's
3691 * easier to waste a few CPU cycles than it is to figure out
3692 * if this is one of those cases.
3693 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003694 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003695 /* On NOMMU, it is more expensive to re-execute shell
3696 * just in order to run echo or test builtin.
3697 * It's better to skip it here and run corresponding
3698 * non-builtin later. */
3699 const struct built_in_command *x;
3700 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003701 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003702 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003703 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003704 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003705#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003706 /* Check if the command matches any functions */
3707 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003708 const struct function *funcp = find_function(argv[0]);
3709 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003710 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003711 }
3712 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003713#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003714
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003715#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003716 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003717 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003718 int a = find_applet_by_name(argv[0]);
3719 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003720# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003721 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003722 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003723 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003724 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003725# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003726 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003727 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003728 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3729 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003730 /* If they called chroot or otherwise made the binary no longer
3731 * executable, fall through */
3732 }
3733 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003734#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003735
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003736#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003737 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003738#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003739 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003740}
3741
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003742/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003743 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003744static void pseudo_exec(nommu_save_t *nommu_save,
3745 struct command *command,
3746 char **argv_expanded) NORETURN;
3747static void pseudo_exec(nommu_save_t *nommu_save,
3748 struct command *command,
3749 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003750{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003751 if (command->argv) {
3752 pseudo_exec_argv(nommu_save, command->argv,
3753 command->assignment_cnt, argv_expanded);
3754 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003755
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003756 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003757 /* Cases when we are here:
3758 * ( list )
3759 * { list } &
3760 * ... | ( list ) | ...
3761 * ... | { list } | ...
3762 */
3763#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003764 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003765 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003766 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003767 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003768 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003769 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003770 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003771#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003772 re_execute_shell(&nommu_save->argv_from_re_execing,
3773 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003774 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003775 G.global_argv + 1,
3776 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003777#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003778 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003779
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003780 /* Case when we are here: ... | >file */
3781 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003782 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003783}
3784
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003785#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003786static const char *get_cmdtext(struct pipe *pi)
3787{
3788 char **argv;
3789 char *p;
3790 int len;
3791
3792 /* This is subtle. ->cmdtext is created only on first backgrounding.
3793 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003794 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003795 if (pi->cmdtext)
3796 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003797 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003798 if (!argv || !argv[0]) {
3799 pi->cmdtext = xzalloc(1);
3800 return pi->cmdtext;
3801 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003802
3803 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003804 do {
3805 len += strlen(*argv) + 1;
3806 } while (*++argv);
3807 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003808 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003809 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003810 do {
3811 len = strlen(*argv);
3812 memcpy(p, *argv, len);
3813 p += len;
3814 *p++ = ' ';
3815 } while (*++argv);
3816 p[-1] = '\0';
3817 return pi->cmdtext;
3818}
3819
Eric Andersenbafd94f2001-05-02 16:11:59 +00003820static void insert_bg_job(struct pipe *pi)
3821{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003822 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003823 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003824
3825 /* Linear search for the ID of the job to use */
3826 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003827 for (job = G.job_list; job; job = job->next)
3828 if (job->jobid >= pi->jobid)
3829 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003830
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003831 /* Add job to the list of running jobs */
3832 jobp = &G.job_list;
3833 while ((job = *jobp) != NULL)
3834 jobp = &job->next;
3835 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003836
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003837 *job = *pi; /* physical copy */
3838 job->next = NULL;
3839 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3840 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003841 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003842 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003843 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003844 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003845 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003846
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003847 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003848 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3849 /* Last command's pid goes to $! */
3850 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3851 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003852}
3853
Eric Andersenbafd94f2001-05-02 16:11:59 +00003854static void remove_bg_job(struct pipe *pi)
3855{
3856 struct pipe *prev_pipe;
3857
Denis Vlasenko87a86552008-07-29 19:43:10 +00003858 if (pi == G.job_list) {
3859 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003860 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003861 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003862 while (prev_pipe->next != pi)
3863 prev_pipe = prev_pipe->next;
3864 prev_pipe->next = pi->next;
3865 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003866 if (G.job_list)
3867 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003868 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003869 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003870}
Eric Andersen028b65b2001-06-28 01:10:11 +00003871
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003872/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003873static void delete_finished_bg_job(struct pipe *pi)
3874{
3875 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003876 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003877 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003878 free(pi);
3879}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003880#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003881
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003882/* Check to see if any processes have exited -- if they
3883 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003884static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003885{
Eric Andersenc798b072001-06-22 06:23:03 +00003886 int attributes;
3887 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003888#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003889 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003890#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003891 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003892 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003893
Denis Vlasenkod5762932009-03-31 11:22:57 +00003894 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3895
Eric Andersenc798b072001-06-22 06:23:03 +00003896 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003897 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003898 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003899
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003900 errno = 0;
3901#if ENABLE_HUSH_FAST
3902 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3903//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3904//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003905 /* There was neither fork nor SIGCHLD since last waitpid */
3906 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003907 if (!G.we_have_children) {
3908 errno = ECHILD;
3909 return -1;
3910 }
3911 if (fg_pipe == NULL) { /* is WNOHANG set? */
3912 /* We have children, but they did not exit
3913 * or stop yet (we saw no SIGCHLD) */
3914 return 0;
3915 }
3916 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3917 }
3918#endif
3919
Denis Vlasenko1359da62007-04-21 23:27:30 +00003920/* Do we do this right?
3921 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003922 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003923 * [3]+ Stopped sleep 20 | false
3924 * bash-3.00# echo $?
3925 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003926 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003927 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003928 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003929 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003930 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003931 int dead;
3932
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003933#if ENABLE_HUSH_FAST
3934 i = G.count_SIGCHLD;
3935#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003936 childpid = waitpid(-1, &status, attributes);
3937 if (childpid <= 0) {
3938 if (childpid && errno != ECHILD)
3939 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003940#if ENABLE_HUSH_FAST
3941 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003942 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003943 G.handled_SIGCHLD = i;
3944//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3945 }
3946#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003947 break;
3948 }
3949 dead = WIFEXITED(status) || WIFSIGNALED(status);
3950
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003951#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003952 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003953 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003954 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3955 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003956 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003957 childpid, WTERMSIG(status), WEXITSTATUS(status));
3958 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003959 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003960 childpid, WEXITSTATUS(status));
3961#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003962 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003963 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003964 for (i = 0; i < fg_pipe->num_cmds; i++) {
3965 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3966 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003967 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003968 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003969 fg_pipe->cmds[i].pid = 0;
3970 fg_pipe->alive_cmds--;
3971 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003972 /* last process gives overall exitstatus */
3973 rcode = WEXITSTATUS(status);
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003974 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00003975 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003976 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003977 */
3978 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003979 int sig = WTERMSIG(status);
3980 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01003981 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
3982 * Maybe we need to use sig | 128? */
3983 rcode = sig + 128;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003984 }
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01003985 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003986 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003987 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003988 fg_pipe->cmds[i].is_stopped = 1;
3989 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003990 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003991 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3992 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3993 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003994 /* All processes in fg pipe have exited or stopped */
3995/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3996 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3997 * and "killall -STOP cat" */
3998 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003999#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004000 if (fg_pipe->alive_cmds)
4001 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004002#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004003 return rcode;
4004 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02004005 if (!fg_pipe->alive_cmds)
4006 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004007 }
4008 /* There are still running processes in the fg pipe */
4009 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00004010 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004011 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00004012 }
4013
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004014#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004015 /* We asked to wait for bg or orphaned children */
4016 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004017 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004018 for (i = 0; i < pi->num_cmds; i++) {
4019 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004020 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00004021 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00004022 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004023 /* Happens when shell is used as init process (init=/bin/sh) */
4024 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004025 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00004026
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004027 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00004028 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00004029 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004030 pi->cmds[i].pid = 0;
4031 pi->alive_cmds--;
4032 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004033 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00004034 printf(JOB_STATUS_FORMAT, pi->jobid,
4035 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004036 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004037 }
4038 } else {
4039 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004040 pi->cmds[i].is_stopped = 1;
4041 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004042 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004043#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004044 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004045
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004046 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00004047}
4048
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004049#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00004050static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4051{
4052 pid_t p;
4053 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04004054 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004055 /* Job finished, move the shell to the foreground */
4056 p = getpgrp(); /* our process group id */
4057 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4058 tcsetpgrp(G_interactive_fd, p);
4059 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00004060 return rcode;
4061}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004062#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00004063
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004064/* Start all the jobs, but don't wait for anything to finish.
4065 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00004066 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00004067 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00004068 * to finish to determine the exit status of the pipe. If the pipe
4069 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00004070 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00004071 * return value.
4072 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00004073 * Returns -1 only if started some children. IOW: we have to
4074 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00004075 *
4076 * The only case when we do not need to [v]fork is when the pipe
4077 * is single, non-backgrounded, non-subshell command. Examples:
4078 * cmd ; ... { list } ; ...
4079 * cmd && ... { list } && ...
4080 * cmd || ... { list } || ...
4081 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4082 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004083 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00004084 *
4085 * Cases when we must fork:
4086 * non-single: cmd | cmd
4087 * backgrounded: cmd & { list } &
4088 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00004089 */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02004090static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004091{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004092 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004093 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004094 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004095 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004096 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004097 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004098 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004099 /* it is not always needed, but we aim to smaller code */
4100 int squirrel[] = { -1, -1, -1 };
4101 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004102
Denis Vlasenko552433b2009-04-04 19:29:21 +00004103 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004104 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004105
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004106 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004107 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004108 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004109 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004110
Denis Vlasenko552433b2009-04-04 19:29:21 +00004111 if (pi->num_cmds != 1
4112 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004113 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00004114 ) {
4115 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004116 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004117
Denis Vlasenko552433b2009-04-04 19:29:21 +00004118 pi->alive_cmds = 1;
4119
4120 debug_printf_exec(": group:%p argv:'%s'\n",
4121 command->group, command->argv ? command->argv[0] : "NONE");
4122
4123 if (command->group) {
4124#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004125 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004126 /* "executing" func () { list } */
4127 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004128
Denis Vlasenkobc569742009-04-12 20:35:19 +00004129 funcp = new_function(command->argv[0]);
4130 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004131 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004132# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004133 funcp->body_as_string = command->group_as_string;
4134 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004135# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004136 command->group = NULL;
4137 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00004138 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4139 funcp->parent_cmd = command;
4140 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004141
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004142 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4143 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00004144 return EXIT_SUCCESS;
4145 }
4146#endif
4147 /* { list } */
4148 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004149 rcode = 1; /* exitcode if redir failed */
4150 if (setup_redirects(command, squirrel) == 0) {
4151 debug_printf_exec(": run_list\n");
4152 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004153 }
Eric Andersen04407e52001-06-07 16:42:05 +00004154 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004155 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004156 debug_leave();
4157 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004158 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004159 }
4160
Denis Vlasenko552433b2009-04-04 19:29:21 +00004161 argv = command->argv ? command->argv : (char **) &null_ptr;
4162 {
4163 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004164#if ENABLE_HUSH_FUNCTIONS
4165 const struct function *funcp;
4166#else
4167 enum { funcp = 0 };
4168#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004169 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004170 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004171
Denis Vlasenko552433b2009-04-04 19:29:21 +00004172 if (argv[command->assignment_cnt] == NULL) {
4173 /* Assignments, but no command */
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004174 /* Ensure redirects take effect (that is, create files).
4175 * Try "a=t >file": */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004176 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004177 restore_redirects(squirrel);
4178 /* Set shell variables */
4179 while (*argv) {
4180 p = expand_string_to_string(*argv);
4181 debug_printf_exec("set shell var:'%s'->'%s'\n",
4182 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004183 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004184 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004185 }
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004186 /* Redirect error sets $? to 1. Othervise,
4187 * if evaluating assignment value set $?, retain it.
4188 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4189 if (rcode == 0)
4190 rcode = G.last_exitcode;
Denis Vlasenko552433b2009-04-04 19:29:21 +00004191 /* Do we need to flag set_local_var() errors?
4192 * "assignment to readonly var" and "putenv error"
4193 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004194 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004195 debug_leave();
4196 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004197 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00004198 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004199
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004200 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004201 if (0) {}
4202#if ENABLE_HUSH_BASH_COMPAT
4203 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004204 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4205 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004206#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004207#ifdef CMD_SINGLEWORD_NOGLOB_COND
4208 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4209 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4210
4211 }
4212#endif
4213 else {
4214 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4215 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004216
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004217 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004218 if (!argv_expanded[0]) {
Denys Vlasenko385cc592010-01-12 06:47:39 +01004219 free(argv_expanded);
Mike Frysinger28736c32009-10-18 01:11:45 -04004220 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004221 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004222 }
4223
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004224 x = find_builtin(argv_expanded[0]);
4225#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004226 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004227 if (!x)
4228 funcp = find_function(argv_expanded[0]);
4229#endif
4230 if (x || funcp) {
4231 if (!funcp) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01004232 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004233 debug_printf("exec with redirects only\n");
4234 rcode = setup_redirects(command, NULL);
4235 goto clean_up_and_ret1;
4236 }
Eric Andersen25f27032001-04-26 23:22:31 +00004237 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004238 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004239 * This is perfect for work that comes after exec().
4240 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004241 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004242 rcode = setup_redirects(command, squirrel);
4243 if (rcode == 0) {
4244 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004245 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004246 if (!funcp) {
4247 debug_printf_exec(": builtin '%s' '%s'...\n",
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004248 x->b_cmd, argv_expanded[1]);
Denys Vlasenko17323a62010-01-28 01:57:05 +01004249 rcode = x->b_function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004250 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004251 }
4252#if ENABLE_HUSH_FUNCTIONS
4253 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004254# if ENABLE_HUSH_LOCAL
4255 struct variable **sv;
4256 sv = G.shadowed_vars_pp;
4257 G.shadowed_vars_pp = &old_vars;
4258# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004259 debug_printf_exec(": function '%s' '%s'...\n",
4260 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004261 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004262# if ENABLE_HUSH_LOCAL
4263 G.shadowed_vars_pp = sv;
4264# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004265 }
4266#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004267 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004268#if ENABLE_FEATURE_SH_STANDALONE
4269 clean_up_and_ret:
4270#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004271 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004272 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004273 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004274 clean_up_and_ret1:
4275 free(argv_expanded);
4276 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004277 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004278 debug_printf_exec("run_pipe return %d\n", rcode);
4279 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004280 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004281
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004282#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004283 i = find_applet_by_name(argv_expanded[0]);
4284 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004285 rcode = setup_redirects(command, squirrel);
4286 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004287 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004288 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004289 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004290 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004291 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004292 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004293 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004294 }
4295#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00004296 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004297 }
4298
Denis Vlasenko552433b2009-04-04 19:29:21 +00004299 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004300 /* NB: argv_expanded may already be created, and that
4301 * might include `cmd` runs! Do not rerun it! We *must*
4302 * use argv_expanded if it's non-NULL */
4303
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004304 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004305 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004306 nextin = 0;
4307
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004308 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004309 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004310#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004311 volatile nommu_save_t nommu_save;
4312 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004313 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004314 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004315 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004316#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004317 command = &(pi->cmds[i]);
4318 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004319 debug_printf_exec(": pipe member '%s' '%s'...\n",
4320 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004321 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004322 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004323 }
Eric Andersen25f27032001-04-26 23:22:31 +00004324
4325 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004326 pipefds.rd = 0;
4327 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004328 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004329 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004330
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004331 command->pid = BB_MMU ? fork() : vfork();
4332 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004333#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004334 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004335 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004336
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004337 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004338 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004339 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004340 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004341 pgrp = pi->pgrp;
4342 if (pgrp < 0) /* true for 1st process only */
4343 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004344 if (setpgid(0, pgrp) == 0
4345 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004346 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004347 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004348 /* We do it in *every* child, not just first,
4349 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004350 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004351 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004352 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004353#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004354 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4355 /* 1st cmd in backgrounded pipe
4356 * should have its stdin /dev/null'ed */
4357 close(0);
4358 if (open(bb_dev_null, O_RDONLY))
4359 xopen("/", O_RDONLY);
4360 } else {
4361 xmove_fd(nextin, 0);
4362 }
4363 xmove_fd(pipefds.wr, 1);
4364 if (pipefds.rd > 1)
4365 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004366 /* Like bash, explicit redirects override pipes,
4367 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004368 if (setup_redirects(command, NULL))
4369 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004370
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004371 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004372 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4373
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004374 /* Stores to nommu_save list of env vars putenv'ed
4375 * (NOMMU, on MMU we don't need that) */
4376 /* cast away volatility... */
4377 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004378 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004379 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004380
Denis Vlasenkof9375282009-04-05 19:13:39 +00004381 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004382#if ENABLE_HUSH_FAST
4383 G.count_SIGCHLD++;
4384//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4385#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004386 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004387#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004388 /* Clean up after vforked child */
4389 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004390 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004391 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004392 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004393#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004394 free(argv_expanded);
4395 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004396 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004397 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00004398 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004399 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004400 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004401#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004402 /* Second and next children need to know pid of first one */
4403 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004404 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004405#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004406 }
Eric Andersen25f27032001-04-26 23:22:31 +00004407
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004408 if (i)
4409 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004410 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004411 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004412 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004413 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004414 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004415
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004416 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004417 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004418 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4419 return 1;
4420 }
4421
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004422 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004423 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004424 return -1;
4425}
4426
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004427#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004428static void debug_print_tree(struct pipe *pi, int lvl)
4429{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004430 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004431 [PIPE_SEQ] = "SEQ",
4432 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004433 [PIPE_OR ] = "OR" ,
4434 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004435 };
4436 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004437 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004438# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004439 [RES_IF ] = "IF" ,
4440 [RES_THEN ] = "THEN" ,
4441 [RES_ELIF ] = "ELIF" ,
4442 [RES_ELSE ] = "ELSE" ,
4443 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004444# endif
4445# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004446 [RES_FOR ] = "FOR" ,
4447 [RES_WHILE] = "WHILE",
4448 [RES_UNTIL] = "UNTIL",
4449 [RES_DO ] = "DO" ,
4450 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004451# endif
4452# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004453 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004454# endif
4455# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004456 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004457 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004458 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004459 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004460 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004461# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004462 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004463 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004464 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004465 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004466 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004467 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004468 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004469# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004470 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004471# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004472 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004473
4474 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004475
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004476 pin = 0;
4477 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004478 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4479 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004480 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004481 while (prn < pi->num_cmds) {
4482 struct command *command = &pi->cmds[prn];
4483 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004484
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004485 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004486 lvl*2, "", prn,
4487 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004488 if (command->group) {
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004489 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004490 CMDTYPE[command->cmd_type],
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004491 argv
4492#if !BB_MMU
4493 , " group_as_string:", command->group_as_string
4494#else
4495 , "", ""
4496#endif
4497 );
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004498 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004499 prn++;
4500 continue;
4501 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004502 if (argv) while (*argv) {
4503 fprintf(stderr, " '%s'", *argv);
4504 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004505 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004506 fprintf(stderr, "\n");
4507 prn++;
4508 }
4509 pi = pi->next;
4510 pin++;
4511 }
4512}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004513#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004514
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004515/* NB: called by pseudo_exec, and therefore must not modify any
4516 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004517static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004518{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004519#if ENABLE_HUSH_CASE
4520 char *case_word = NULL;
4521#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004522#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004523 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004524 char **for_lcur = NULL;
4525 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004526#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004527 smallint last_followup;
4528 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004529#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004530 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004531#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004532 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004533#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004534#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004535 smallint rword; /* enum reserved_style */
4536 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004537#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004538
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004539 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004540 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004541
Denis Vlasenko06810332007-05-21 23:30:54 +00004542#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004543 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004544 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4545 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004546 continue;
4547 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004548 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004549 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004550 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004551 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004552 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004553 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004554 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004555 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004556 continue;
4557 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004558 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4559 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004560 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004561 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004562 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004563 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004564 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004565 }
4566 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004567#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004568
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004569 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004570 * in order to return, no direct "return" statements please.
4571 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004572
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004573#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004574 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004575#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004576
Denis Vlasenko0e151382009-04-06 18:40:31 +00004577#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004578 rword = RES_NONE;
4579 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004580#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004581 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004582 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004583
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004584 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004585 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004586 if (G.flag_SIGINT)
4587 break;
4588
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004589 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004590 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4591 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004592#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004593 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004594 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004595 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004596 /* start of a loop: remember where loop starts */
4597 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004598 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004599 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004600#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004601 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004602 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004603 if ((rcode == 0 && last_followup == PIPE_OR)
4604 || (rcode != 0 && last_followup == PIPE_AND)
4605 ) {
4606 /* It is "<true> || CMD" or "<false> && CMD"
4607 * and we should not execute CMD */
4608 debug_printf_exec("skipped cmd because of || or &&\n");
4609 last_followup = pi->followup;
4610 continue;
4611 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004612 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004613 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004614 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004615#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004616 if (cond_code) {
4617 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004618 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004619 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004620 /* "if <false> THEN cmd": skip cmd */
4621 continue;
4622 }
4623 } else {
4624 if (rword == RES_ELSE || rword == RES_ELIF) {
4625 /* "if <true> then ... ELSE/ELIF cmd":
4626 * skip cmd and all following ones */
4627 break;
4628 }
4629 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004630#endif
4631#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004632 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004633 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004634 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004635
4636 static const char encoded_dollar_at[] ALIGN1 = {
4637 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4638 }; /* encoded representation of "$@" */
4639 static const char *const encoded_dollar_at_argv[] = {
4640 encoded_dollar_at, NULL
4641 }; /* argv list with one element: "$@" */
4642 char **vals;
4643
4644 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004645 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004646 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004647 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004648 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004649 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004650 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004651 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004652 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004653 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004654 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004655 debug_print_strings("for_list made from", vals);
4656 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004657 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004658 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004659 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004660 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004661 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004662 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004663 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004664 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004665 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004666 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004667 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004668 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004669 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 +02004670 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004671 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004672 if (rword == RES_IN) {
4673 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4674 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004675 if (rword == RES_DONE) {
4676 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004677 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004678#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004679#if ENABLE_HUSH_CASE
4680 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004681 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004682 continue;
4683 }
4684 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004685 char **argv;
4686
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004687 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4688 break;
4689 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004690 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004691 while (*argv) {
4692 char *pattern = expand_string_to_string(*argv);
4693 /* TODO: which FNM_xxx flags to use? */
4694 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4695 free(pattern);
4696 if (cond_code == 0) { /* match! we will execute this branch */
4697 free(case_word); /* make future "word)" stop */
4698 case_word = NULL;
4699 break;
4700 }
4701 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004702 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004703 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004704 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004705 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004706 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004707 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004708 }
4709#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004710 /* Just pressing <enter> in shell should check for jobs.
4711 * OTOH, in non-interactive shell this is useless
4712 * and only leads to extra job checks */
4713 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004714 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004715 goto check_jobs_and_continue;
4716 continue;
4717 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004718
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004719 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004720 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004721 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004722 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004723 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004724 {
4725 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004726#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004727 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004728#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004729 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4730 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004731 /* We ran a builtin, function, or group.
4732 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004733 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004734 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004735 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004736 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004737#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004738 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004739 if (G.flag_break_continue) {
4740 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004741 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004742 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004743 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004744 G.depth_break_continue--;
4745 if (G.depth_break_continue == 0)
4746 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004747 /* else: e.g. "continue 2" should *break* once, *then* continue */
4748 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004749 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004750 goto check_jobs_and_break;
4751 /* "continue": simulate end of loop */
4752 rword = RES_DONE;
4753 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004754 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004755#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004756#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004757 if (G.flag_return_in_progress == 1) {
4758 /* same as "goto check_jobs_and_break" */
4759 checkjobs(NULL);
4760 break;
4761 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004762#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004763 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004764 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004765 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004766 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4767 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004768 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004769#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004770 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004771 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004772#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004773 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004774 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004775 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004776#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004777 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004778 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004779 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004780 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004781 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004782 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004783#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004784 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004785 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004786 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004787 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004788 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004789 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004790 }
4791 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004792
4793 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004794#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004795 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004796 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004797#endif
4798#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004799 /* Beware of "while false; true; do ..."! */
4800 if (pi->next && pi->next->res_word == RES_DO) {
4801 if (rword == RES_WHILE) {
4802 if (rcode) {
4803 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004804 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004805 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4806 goto check_jobs_and_break;
4807 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004808 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004809 if (rword == RES_UNTIL) {
4810 if (!rcode) {
4811 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004812 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004813 checkjobs(NULL);
4814 break;
4815 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004816 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004817 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004818#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004819
4820 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004821 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004822 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004823
4824#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004825 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004826#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004827#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004828 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004829 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004830 free(for_list);
4831#endif
4832#if ENABLE_HUSH_CASE
4833 free(case_word);
4834#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004835 debug_leave();
4836 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004837 return rcode;
4838}
4839
Eric Andersen25f27032001-04-26 23:22:31 +00004840/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004841static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004842{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004843 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004844 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004845 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004846 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004847 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004848 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004849 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004850 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004851 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004852 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004853 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004854 return rcode;
4855}
4856
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004857
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004858static struct pipe *new_pipe(void)
4859{
Eric Andersen25f27032001-04-26 23:22:31 +00004860 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004861 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004862 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004863 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004864 return pi;
4865}
4866
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004867/* Command (member of a pipe) is complete, or we start a new pipe
4868 * if ctx->command is NULL.
4869 * No errors possible here.
4870 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004871static int done_command(struct parse_context *ctx)
4872{
4873 /* The command is really already in the pipe structure, so
4874 * advance the pipe counter and make a new, null command. */
4875 struct pipe *pi = ctx->pipe;
4876 struct command *command = ctx->command;
4877
4878 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004879 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004880 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004881 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004882 }
4883 pi->num_cmds++;
4884 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004885 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004886 } else {
4887 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4888 }
4889
4890 /* Only real trickiness here is that the uncommitted
4891 * command structure is not counted in pi->num_cmds. */
4892 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004893 ctx->command = command = &pi->cmds[pi->num_cmds];
4894 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004895 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004896 return pi->num_cmds; /* used only for 0/nonzero check */
4897}
4898
4899static void done_pipe(struct parse_context *ctx, pipe_style type)
4900{
4901 int not_null;
4902
4903 debug_printf_parse("done_pipe entered, followup %d\n", type);
4904 /* Close previous command */
4905 not_null = done_command(ctx);
4906 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004907#if HAS_KEYWORDS
4908 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4909 ctx->ctx_inverted = 0;
4910 ctx->pipe->res_word = ctx->ctx_res_w;
4911#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004912
4913 /* Without this check, even just <enter> on command line generates
4914 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004915 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004916 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004917#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004918 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004919#endif
4920#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004921 || ctx->ctx_res_w == RES_DONE
4922 || ctx->ctx_res_w == RES_FOR
4923 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004924#endif
4925#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004926 || ctx->ctx_res_w == RES_ESAC
4927#endif
4928 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004929 struct pipe *new_p;
4930 debug_printf_parse("done_pipe: adding new pipe: "
4931 "not_null:%d ctx->ctx_res_w:%d\n",
4932 not_null, ctx->ctx_res_w);
4933 new_p = new_pipe();
4934 ctx->pipe->next = new_p;
4935 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004936 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004937 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004938 * This is used to control execution.
4939 * RES_FOR and RES_IN are NOT sticky (needed to support
4940 * cases where variable or value happens to match a keyword):
4941 */
4942#if ENABLE_HUSH_LOOPS
4943 if (ctx->ctx_res_w == RES_FOR
4944 || ctx->ctx_res_w == RES_IN)
4945 ctx->ctx_res_w = RES_NONE;
4946#endif
4947#if ENABLE_HUSH_CASE
4948 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004949 ctx->ctx_res_w = RES_CASE_BODY;
4950 if (ctx->ctx_res_w == RES_CASE)
4951 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004952#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004953 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004954 /* Create the memory for command, roughly:
4955 * ctx->pipe->cmds = new struct command;
4956 * ctx->command = &ctx->pipe->cmds[0];
4957 */
4958 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004959 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004960 }
4961 debug_printf_parse("done_pipe return\n");
4962}
4963
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004964static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004965{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004966 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004967 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004968 /* Create the memory for command, roughly:
4969 * ctx->pipe->cmds = new struct command;
4970 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004971 */
4972 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004973}
4974
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004975/* If a reserved word is found and processed, parse context is modified
4976 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004977 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004978#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004979struct reserved_combo {
4980 char literal[6];
4981 unsigned char res;
4982 unsigned char assignment_flag;
4983 int flag;
4984};
4985enum {
4986 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004987# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004988 FLAG_IF = (1 << RES_IF ),
4989 FLAG_THEN = (1 << RES_THEN ),
4990 FLAG_ELIF = (1 << RES_ELIF ),
4991 FLAG_ELSE = (1 << RES_ELSE ),
4992 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004993# endif
4994# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004995 FLAG_FOR = (1 << RES_FOR ),
4996 FLAG_WHILE = (1 << RES_WHILE),
4997 FLAG_UNTIL = (1 << RES_UNTIL),
4998 FLAG_DO = (1 << RES_DO ),
4999 FLAG_DONE = (1 << RES_DONE ),
5000 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005001# endif
5002# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005003 FLAG_MATCH = (1 << RES_MATCH),
5004 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005005# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005006 FLAG_START = (1 << RES_XXXX ),
5007};
5008
5009static const struct reserved_combo* match_reserved_word(o_string *word)
5010{
Eric Andersen25f27032001-04-26 23:22:31 +00005011 /* Mostly a list of accepted follow-up reserved words.
5012 * FLAG_END means we are done with the sequence, and are ready
5013 * to turn the compound list into a command.
5014 * FLAG_START means the word must start a new compound list.
5015 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005016 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005017# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005018 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5019 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5020 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5021 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5022 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5023 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005024# endif
5025# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005026 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5027 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5028 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5029 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5030 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5031 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005032# endif
5033# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005034 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5035 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005036# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005037 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005038 const struct reserved_combo *r;
5039
5040 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5041 if (strcmp(word->data, r->literal) == 0)
5042 return r;
5043 }
5044 return NULL;
5045}
Denis Vlasenkobb929512009-04-16 10:59:40 +00005046/* Return 0: not a keyword, 1: keyword
5047 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005048static int reserved_word(o_string *word, struct parse_context *ctx)
5049{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005050# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005051 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005052 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005053 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005054# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005055 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005056
Denis Vlasenkobb929512009-04-16 10:59:40 +00005057 if (word->o_quoted)
5058 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005059 r = match_reserved_word(word);
5060 if (!r)
5061 return 0;
5062
5063 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005064# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005065 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5066 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005067 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005068 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005069# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005070 if (r->flag == 0) { /* '!' */
5071 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005072 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00005073 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00005074 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005075 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005076 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005077 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005078 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005079 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005080
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005081 old = xmalloc(sizeof(*old));
5082 debug_printf_parse("push stack %p\n", old);
5083 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005084 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005085 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005086 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005087 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005088 ctx->ctx_res_w = RES_SNTX;
5089 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005090 } else {
5091 /* "{...} fi" is ok. "{...} if" is not
5092 * Example:
5093 * if { echo foo; } then { echo bar; } fi */
5094 if (ctx->command->group)
5095 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005096 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00005097
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005098 ctx->ctx_res_w = r->res;
5099 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005100 word->o_assignment = r->assignment_flag;
5101
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005102 if (ctx->old_flag & FLAG_END) {
5103 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005104
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005105 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005106 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005107 old = ctx->stack;
5108 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005109 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005110# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005111 o_addstr(&old->as_string, ctx->as_string.data);
5112 o_free_unsafe(&ctx->as_string);
5113 old->command->group_as_string = xstrdup(old->as_string.data);
5114 debug_printf_parse("pop, remembering as:'%s'\n",
5115 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005116# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005117 *ctx = *old; /* physical copy */
5118 free(old);
5119 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005120 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005121}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005122#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00005123
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005124/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005125 * Normal return is 0. Syntax errors return 1.
5126 * Note: on return, word is reset, but not o_free'd!
5127 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005128static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005129{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005130 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00005131
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005132 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005133 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005134 debug_printf_parse("done_word return 0: true null, ignored\n");
5135 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005136 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005137
Eric Andersen25f27032001-04-26 23:22:31 +00005138 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005139 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5140 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005141 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5142 * "2.7 Redirection
5143 * ...the word that follows the redirection operator
5144 * shall be subjected to tilde expansion, parameter expansion,
5145 * command substitution, arithmetic expansion, and quote
5146 * removal. Pathname expansion shall not be performed
5147 * on the word by a non-interactive shell; an interactive
5148 * shell may perform it, but shall do so only when
5149 * the expansion would result in one word."
5150 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005151 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005152 /* Cater for >\file case:
5153 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5154 * Same with heredocs:
5155 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5156 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005157 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5158 unbackslash(ctx->pending_redirect->rd_filename);
5159 /* Is it <<"HEREDOC"? */
5160 if (word->o_quoted) {
5161 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5162 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005163 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005164 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005165 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00005166 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005167 /* If this word wasn't an assignment, next ones definitely
5168 * can't be assignments. Even if they look like ones. */
5169 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5170 && word->o_assignment != WORD_IS_KEYWORD
5171 ) {
5172 word->o_assignment = NOT_ASSIGNMENT;
5173 } else {
5174 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5175 command->assignment_cnt++;
5176 word->o_assignment = MAYBE_ASSIGNMENT;
5177 }
5178
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005179#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005180# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00005181 if (ctx->ctx_dsemicolon
5182 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5183 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00005184 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005185 /* ctx->ctx_res_w = RES_MATCH; */
5186 ctx->ctx_dsemicolon = 0;
5187 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005188# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005189 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005190# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005191 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5192 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005193# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005194# if ENABLE_HUSH_CASE
5195 && ctx->ctx_res_w != RES_CASE
5196# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005197 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005198 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005199 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005200 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005201 debug_printf_parse("done_word return %d\n",
5202 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005203 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005204 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005205# ifdef CMD_SINGLEWORD_NOGLOB_COND
5206 if (strcmp(word->data, "export") == 0
5207# if ENABLE_HUSH_LOCAL
5208 || strcmp(word->data, "local") == 0
5209# endif
5210 ) {
5211 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5212 } else
5213# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005214# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005215 if (strcmp(word->data, "[[") == 0) {
5216 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5217 }
5218 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005219# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005220 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005221#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005222 if (command->group) {
5223 /* "{ echo foo; } echo bar" - bad */
5224 syntax_error_at(word->data);
5225 debug_printf_parse("done_word return 1: syntax error, "
5226 "groups and arglists don't mix\n");
5227 return 1;
5228 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005229 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005230 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5231 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005232 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005233 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005234 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005235 char *p = word->data;
5236 while (p[0] == SPECIAL_VAR_SYMBOL
5237 && (p[1] & 0x7f) == '@'
5238 && p[2] == SPECIAL_VAR_SYMBOL
5239 ) {
5240 p += 3;
5241 }
5242 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005243 /* saw no "$@", or not only "$@" but some
5244 * real text is there too */
5245 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005246 * e.g. "", $empty"" etc to not disappear */
5247 o_addchr(word, SPECIAL_VAR_SYMBOL);
5248 o_addchr(word, SPECIAL_VAR_SYMBOL);
5249 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005250 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005251 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005252 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005253 }
Eric Andersen25f27032001-04-26 23:22:31 +00005254
Denis Vlasenko06810332007-05-21 23:30:54 +00005255#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005256 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005257 if (word->o_quoted
5258 || !is_well_formed_var_name(command->argv[0], '\0')
5259 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005260 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005261 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005262 return 1;
5263 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005264 /* Force FOR to have just one word (variable name) */
5265 /* NB: basically, this makes hush see "for v in ..."
5266 * syntax as if it is "for v; in ...". FOR and IN become
5267 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005268 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005269 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005270#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005271#if ENABLE_HUSH_CASE
5272 /* Force CASE to have just one word */
5273 if (ctx->ctx_res_w == RES_CASE) {
5274 done_pipe(ctx, PIPE_SEQ);
5275 }
5276#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005277
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005278 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005279
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005280 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005281 return 0;
5282}
5283
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005284
5285/* Peek ahead in the input to find out if we have a "&n" construct,
5286 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005287 * Return:
5288 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5289 * REDIRFD_SYNTAX_ERR if syntax error,
5290 * REDIRFD_TO_FILE if no & was seen,
5291 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005292 */
5293#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005294#define parse_redir_right_fd(as_string, input) \
5295 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005296#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005297static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005298{
5299 int ch, d, ok;
5300
5301 ch = i_peek(input);
5302 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005303 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005304
5305 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005306 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005307 ch = i_peek(input);
5308 if (ch == '-') {
5309 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005310 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005311 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005312 }
5313 d = 0;
5314 ok = 0;
5315 while (ch != EOF && isdigit(ch)) {
5316 d = d*10 + (ch-'0');
5317 ok = 1;
5318 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005319 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005320 ch = i_peek(input);
5321 }
5322 if (ok) return d;
5323
5324//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5325
5326 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005327 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005328}
5329
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005330/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005331 */
5332static int parse_redirect(struct parse_context *ctx,
5333 int fd,
5334 redir_type style,
5335 struct in_str *input)
5336{
5337 struct command *command = ctx->command;
5338 struct redir_struct *redir;
5339 struct redir_struct **redirp;
5340 int dup_num;
5341
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005342 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005343 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005344 /* Check for a '>&1' type redirect */
5345 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5346 if (dup_num == REDIRFD_SYNTAX_ERR)
5347 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005348 } else {
5349 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005350 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005351 if (dup_num) { /* <<-... */
5352 ch = i_getch(input);
5353 nommu_addchr(&ctx->as_string, ch);
5354 ch = i_peek(input);
5355 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005356 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005357
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005358 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005359 int ch = i_peek(input);
5360 if (ch == '|') {
5361 /* >|FILE redirect ("clobbering" >).
5362 * Since we do not support "set -o noclobber" yet,
5363 * >| and > are the same for now. Just eat |.
5364 */
5365 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005366 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005367 }
5368 }
5369
5370 /* Create a new redir_struct and append it to the linked list */
5371 redirp = &command->redirects;
5372 while ((redir = *redirp) != NULL) {
5373 redirp = &(redir->next);
5374 }
5375 *redirp = redir = xzalloc(sizeof(*redir));
5376 /* redir->next = NULL; */
5377 /* redir->rd_filename = NULL; */
5378 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005379 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005380
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005381 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5382 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005383
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005384 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005385 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005386 /* Erik had a check here that the file descriptor in question
5387 * is legit; I postpone that to "run time"
5388 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005389 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5390 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005391 } else {
5392 /* Set ctx->pending_redirect, so we know what to do at the
5393 * end of the next parsed word. */
5394 ctx->pending_redirect = redir;
5395 }
5396 return 0;
5397}
5398
Eric Andersen25f27032001-04-26 23:22:31 +00005399/* If a redirect is immediately preceded by a number, that number is
5400 * supposed to tell which file descriptor to redirect. This routine
5401 * looks for such preceding numbers. In an ideal world this routine
5402 * needs to handle all the following classes of redirects...
5403 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5404 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5405 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5406 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005407 *
5408 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5409 * "2.7 Redirection
5410 * ... If n is quoted, the number shall not be recognized as part of
5411 * the redirection expression. For example:
5412 * echo \2>a
5413 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005414 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005415 *
5416 * A -1 return means no valid number was found,
5417 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005418 */
5419static int redirect_opt_num(o_string *o)
5420{
5421 int num;
5422
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005423 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005424 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005425 num = bb_strtou(o->data, NULL, 10);
5426 if (errno || num < 0)
5427 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005428 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005429 return num;
5430}
5431
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005432#if BB_MMU
5433#define fetch_till_str(as_string, input, word, skip_tabs) \
5434 fetch_till_str(input, word, skip_tabs)
5435#endif
5436static char *fetch_till_str(o_string *as_string,
5437 struct in_str *input,
5438 const char *word,
5439 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005440{
5441 o_string heredoc = NULL_O_STRING;
5442 int past_EOL = 0;
5443 int ch;
5444
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005445 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005446 while (1) {
5447 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005448 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005449 if (ch == '\n') {
5450 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5451 heredoc.data[past_EOL] = '\0';
5452 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5453 return heredoc.data;
5454 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005455 do {
5456 o_addchr(&heredoc, ch);
5457 past_EOL = heredoc.length;
5458 jump_in:
5459 do {
5460 ch = i_getch(input);
5461 nommu_addchr(as_string, ch);
5462 } while (skip_tabs && ch == '\t');
5463 } while (ch == '\n');
5464 }
5465 if (ch == EOF) {
5466 o_free_unsafe(&heredoc);
5467 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005468 }
5469 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005470 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005471 }
5472}
5473
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005474/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5475 * and load them all. There should be exactly heredoc_cnt of them.
5476 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005477static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5478{
5479 struct pipe *pi = ctx->list_head;
5480
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005481 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005482 int i;
5483 struct command *cmd = pi->cmds;
5484
5485 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5486 pi->num_cmds,
5487 cmd->argv ? cmd->argv[0] : "NONE");
5488 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005489 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005490
5491 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5492 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005493 while (redir) {
5494 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005495 char *p;
5496
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005497 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005498 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005499 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005500 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005501 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005502 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005503 return 1;
5504 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005505 free(redir->rd_filename);
5506 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005507 heredoc_cnt--;
5508 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005509 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005510 }
5511 cmd++;
5512 }
5513 pi = pi->next;
5514 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005515#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005516 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005517 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005518 bb_error_msg_and_die("heredoc BUG 2");
5519#endif
5520 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005521}
5522
5523
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005524#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005525static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005526{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005527 pid_t pid;
5528 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005529# if !BB_MMU
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01005530 char **to_free = NULL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005531# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005532
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005533 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00005534 pid = BB_MMU ? fork() : vfork();
5535 if (pid < 0)
5536 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005537
Denis Vlasenko05743d72008-02-10 12:10:08 +00005538 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005539 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005540 /* Process substitution is not considered to be usual
5541 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005542 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5543 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005544 bb_signals(0
5545 + (1 << SIGTSTP)
5546 + (1 << SIGTTIN)
5547 + (1 << SIGTTOU)
5548 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005549 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005550 close(channel[0]); /* NB: close _first_, then move fd! */
5551 xmove_fd(channel[1], 1);
5552 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005553 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005554 /* Awful hack for `trap` or $(trap).
5555 *
5556 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5557 * contains an example where "trap" is executed in a subshell:
5558 *
5559 * save_traps=$(trap)
5560 * ...
5561 * eval "$save_traps"
5562 *
5563 * Standard does not say that "trap" in subshell shall print
5564 * parent shell's traps. It only says that its output
5565 * must have suitable form, but then, in the above example
5566 * (which is not supposed to be normative), it implies that.
5567 *
5568 * bash (and probably other shell) does implement it
5569 * (traps are reset to defaults, but "trap" still shows them),
5570 * but as a result, "trap" logic is hopelessly messed up:
5571 *
5572 * # trap
5573 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5574 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5575 * # true | trap <--- trap is in subshell - no output (ditto)
5576 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5577 * trap -- 'echo Ho' SIGWINCH
5578 * # echo `(trap)` <--- in subshell in subshell - output
5579 * trap -- 'echo Ho' SIGWINCH
5580 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5581 * trap -- 'echo Ho' SIGWINCH
5582 *
5583 * The rules when to forget and when to not forget traps
5584 * get really complex and nonsensical.
5585 *
5586 * Our solution: ONLY bare $(trap) or `trap` is special.
5587 */
5588 s = skip_whitespace(s);
5589 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5590 {
5591 static const char *const argv[] = { NULL, NULL };
5592 builtin_trap((char**)argv);
5593 exit(0); /* not _exit() - we need to fflush */
5594 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005595# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005596 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005597 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005598 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005599# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005600 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005601 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5602 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005603 * echo OK
5604 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005605 re_execute_shell(&to_free,
5606 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005607 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005608 G.global_argv + 1,
5609 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005610# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005611 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005612
5613 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005614 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005615# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005616 G.count_SIGCHLD++;
5617//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 +02005618# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005619 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005620# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005621 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005622# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005623 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005624 close_on_exec_on(channel[0]);
5625 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005626}
5627
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005628/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005629static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005630{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005631 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005632 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005633 pid_t pid;
5634 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005635
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005636 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005637
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005638 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005639 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005640 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005641 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005642 if (ch == '\n') {
5643 eol_cnt++;
5644 continue;
5645 }
5646 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005647 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005648 eol_cnt--;
5649 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005650 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005651 }
5652
Denys Vlasenko647553a2009-11-15 19:58:19 +01005653 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005654 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005655 /* We need to extract exitcode. Test case
5656 * "true; echo `sleep 1; false` $?"
5657 * should print 1 */
5658 safe_waitpid(pid, &status, 0);
5659 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5660 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005661}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005662#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005663
Denys Vlasenkoc2704542009-11-20 19:14:19 +01005664#if !ENABLE_HUSH_FUNCTIONS
5665#define parse_group(dest, ctx, input, ch) \
5666 parse_group(ctx, input, ch)
5667#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005668static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005669 struct in_str *input, int ch)
5670{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005671 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005672 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005673 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005674 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005675 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005676 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005677
5678 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005679#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005680 if (ch == '(' && !dest->o_quoted) {
5681 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005682 if (done_word(dest, ctx))
5683 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005684 if (!command->argv)
5685 goto skip; /* (... */
5686 if (command->argv[1]) { /* word word ... (... */
5687 syntax_error_unexpected_ch('(');
5688 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005689 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005690 /* it is "word(..." or "word (..." */
5691 do
5692 ch = i_getch(input);
5693 while (ch == ' ' || ch == '\t');
5694 if (ch != ')') {
5695 syntax_error_unexpected_ch(ch);
5696 return 1;
5697 }
5698 nommu_addchr(&ctx->as_string, ch);
5699 do
5700 ch = i_getch(input);
5701 while (ch == ' ' || ch == '\t' || ch == '\n');
5702 if (ch != '{') {
5703 syntax_error_unexpected_ch(ch);
5704 return 1;
5705 }
5706 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005707 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005708 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005709 }
5710#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005711
5712#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005713 if (command->argv /* word [word]{... */
5714 || dest->length /* word{... */
5715 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005716 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005717 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005718 debug_printf_parse("parse_group return 1: "
5719 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005720 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005721 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005722#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005723
5724#if ENABLE_HUSH_FUNCTIONS
5725 skip:
5726#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005727 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005728 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005729 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005730 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005731 } else {
5732 /* bash does not allow "{echo...", requires whitespace */
5733 ch = i_getch(input);
5734 if (ch != ' ' && ch != '\t' && ch != '\n') {
5735 syntax_error_unexpected_ch(ch);
5736 return 1;
5737 }
5738 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005739 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005740
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005741 {
5742#if !BB_MMU
5743 char *as_string = NULL;
5744#endif
5745 pipe_list = parse_stream(&as_string, input, endch);
5746#if !BB_MMU
5747 if (as_string)
5748 o_addstr(&ctx->as_string, as_string);
5749#endif
5750 /* empty ()/{} or parse error? */
5751 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005752 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005753#if !BB_MMU
5754 free(as_string);
5755#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005756 debug_printf_parse("parse_group return 1: "
5757 "parse_stream returned %p\n", pipe_list);
5758 return 1;
5759 }
5760 command->group = pipe_list;
5761#if !BB_MMU
5762 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5763 command->group_as_string = as_string;
5764 debug_printf_parse("end of group, remembering as:'%s'\n",
5765 command->group_as_string);
5766#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005767 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005768 debug_printf_parse("parse_group return 0\n");
5769 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005770 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005771}
5772
Mike Frysinger98c52642009-04-02 10:02:37 +00005773#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005774/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005775static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005776/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005777static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005778{
5779 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005780 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005781 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005782 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005783 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005784 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005785 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005786 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005787 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005788 }
5789}
5790/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005791static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005792{
5793 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005794 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005795 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005796 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005797 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005798 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005799 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005800 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005801 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005802 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005803 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005804 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005805 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005806 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005807 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005808 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005809 continue;
5810 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005811 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005812 }
5813}
5814/* Process `cmd` - copy contents until "`" is seen. Complicated by
5815 * \` quoting.
5816 * "Within the backquoted style of command substitution, backslash
5817 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5818 * The search for the matching backquote shall be satisfied by the first
5819 * backquote found without a preceding backslash; during this search,
5820 * if a non-escaped backquote is encountered within a shell comment,
5821 * a here-document, an embedded command substitution of the $(command)
5822 * form, or a quoted string, undefined results occur. A single-quoted
5823 * or double-quoted string that begins, but does not end, within the
5824 * "`...`" sequence produces undefined results."
5825 * Example Output
5826 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5827 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005828static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005829{
5830 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005831 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005832 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005833 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005834 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005835 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005836 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005837 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005838 if (ch == '\\') {
5839 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005840 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005841 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005842 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005843 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005844 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005845 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005846 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005847 ch = ch2;
5848 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005849 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005850 }
5851}
5852/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5853 * quoting and nested ()s.
5854 * "With the $(command) style of command substitution, all characters
5855 * following the open parenthesis to the matching closing parenthesis
5856 * constitute the command. Any valid shell script can be used for command,
5857 * except a script consisting solely of redirections which produces
5858 * unspecified results."
5859 * Example Output
5860 * echo $(echo '(TEST)' BEST) (TEST) BEST
5861 * echo $(echo 'TEST)' BEST) TEST) BEST
5862 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5863 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005864static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005865{
5866 int count = 0;
5867 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005868 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005869 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005870 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005871 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005872 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005873 if (ch == '(')
5874 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005875 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005876 if (--count < 0) {
5877 if (!dbl)
5878 break;
5879 if (i_peek(input) == ')') {
5880 i_getch(input);
5881 break;
5882 }
5883 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005884 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005885 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005886 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005887 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005888 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005889 continue;
5890 }
5891 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005892 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005893 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005894 continue;
5895 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005896 if (ch == '\\') {
5897 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005898 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005899 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005900 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005901 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005902 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005903 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005904 continue;
5905 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005906 }
5907}
Mike Frysinger98c52642009-04-02 10:02:37 +00005908#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005909
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005910/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005911#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005912#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005913 handle_dollar(dest, input)
5914#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005915static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005916 o_string *dest,
5917 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005918{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005919 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005920 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005921
5922 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005923 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005924 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005925 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005926 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005927 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005928 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005929 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005930 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005931 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005932 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005933 if (!isalnum(ch) && ch != '_')
5934 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005935 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005936 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005937 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005938 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005939 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005940 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005941 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005942 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005943 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005944 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005945 o_addchr(dest, ch | quote_mask);
5946 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005947 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005948 case '$': /* pid */
5949 case '!': /* last bg pid */
5950 case '?': /* last exit code */
5951 case '#': /* number of args */
5952 case '*': /* args */
5953 case '@': /* args */
5954 goto make_one_char_var;
5955 case '{': {
5956 bool first_char, all_digits;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02005957 bool in_expansion_param;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005958
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005959 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005960 nommu_addchr(as_string, ch);
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005961 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5962
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02005963// TODO: need to handle "a=ab}; echo ${a%\}}"
5964// and "a=abc; c=c; echo ${a%${c}}"
5965 in_expansion_param = false;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005966 first_char = true;
5967 all_digits = false;
5968 while (1) {
5969 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005970 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005971 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005972 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005973 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005974
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005975 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005976 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005977 /* ${#var}: length of var contents */
5978 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005979 }
5980 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005981 all_digits = true;
5982 goto char_ok;
5983 }
Mike Frysingerdc3bc402009-06-01 14:09:09 -04005984 /* They're being verbose and doing ${?} */
5985 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5986 goto char_ok;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005987 }
5988
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02005989 if (!in_expansion_param
5990 && ( (all_digits && !isdigit(ch)) /* met non-digit: 123w */
5991 || (!all_digits && !isalnum(ch) && ch != '_') /* met non-name char: abc% */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005992 )
5993 ) {
5994 /* handle parameter expansions
5995 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5996 */
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02005997 if (first_char /* bad (empty var name): "${%..." */
5998 || !strchr("%#:-=+?", ch) /* bad: "${var<bad_char>..." */
5999 ) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006000 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006001 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
6002 return 1;
6003 }
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02006004 in_expansion_param = true;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006005 }
6006 char_ok:
6007 debug_printf_parse(": '%c'\n", ch);
6008 o_addchr(dest, ch | quote_mask);
6009 quote_mask = 0;
6010 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006011 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006012 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6013 break;
6014 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006015#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006016 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006017# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006018 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006019# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006020 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006021 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006022# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006023 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006024 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006025 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006026 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6027 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006028# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006029 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006030# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006031 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006032# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006033 if (as_string) {
6034 o_addstr(as_string, dest->data + pos);
6035 o_addchr(as_string, ')');
6036 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006037 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006038# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006039 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006040 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006041 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006042# endif
6043# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006044 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6045 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006046# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006047 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006048# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006049 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006050# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006051 if (as_string) {
6052 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006053 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006054 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006055# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006056 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006057# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006058 break;
6059 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006060#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006061 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006062 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006063 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006064 ch = i_peek(input);
6065 if (isalnum(ch)) { /* it's $_name or $_123 */
6066 ch = '_';
6067 goto make_var;
6068 }
6069 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02006070 /* TODO: $_ and $-: */
6071 /* $_ Shell or shell script name; or last argument of last command
6072 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6073 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006074 /* $- Option flags set by set builtin or shell options (-i etc) */
6075 default:
6076 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00006077 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006078 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00006079 return 0;
6080}
6081
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006082#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006083#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006084 parse_stream_dquoted(dest, input, dquote_end)
6085#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006086static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006087 o_string *dest,
6088 struct in_str *input,
6089 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006090{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006091 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006092 int next;
6093
6094 again:
6095 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006096 if (ch != EOF)
6097 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006098 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006099 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006100 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006101 debug_printf_parse("parse_stream_dquoted return 0\n");
6102 return 0;
6103 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006104 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006105 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006106 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006107 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006108 }
6109 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006110 if (ch != '\n') {
6111 next = i_peek(input);
6112 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006113 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006114 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006115 if (ch == '\\') {
6116 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006117 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006118 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006119 }
6120 /* bash:
6121 * "The backslash retains its special meaning [in "..."]
6122 * only when followed by one of the following characters:
6123 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006124 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006125 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006126 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00006127 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006128 if (ch != '\n') {
6129 o_addqchr(dest, ch);
6130 nommu_addchr(as_string, ch);
6131 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006132 } else {
6133 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00006134 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006135 }
6136 goto again;
6137 }
6138 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006139 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006140 debug_printf_parse("parse_stream_dquoted return 1: "
6141 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006142 return 1;
6143 }
6144 goto again;
6145 }
6146#if ENABLE_HUSH_TICK
6147 if (ch == '`') {
6148 //int pos = dest->length;
6149 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6150 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006151 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006152 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6153 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00006154 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006155 }
6156#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00006157 o_addQchr(dest, ch);
6158 if (ch == '='
6159 && (dest->o_assignment == MAYBE_ASSIGNMENT
6160 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006161 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00006162 ) {
6163 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6164 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006165 goto again;
6166}
6167
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006168/*
6169 * Scan input until EOF or end_trigger char.
6170 * Return a list of pipes to execute, or NULL on EOF
6171 * or if end_trigger character is met.
6172 * On syntax error, exit is shell is not interactive,
6173 * reset parsing machinery and start parsing anew,
6174 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006175 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006176static struct pipe *parse_stream(char **pstring,
6177 struct in_str *input,
6178 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006179{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006180 struct parse_context ctx;
6181 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006182 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006183 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006184
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006185 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006186 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006187 * found. When recursing, quote state is passed in via dest->o_escape.
6188 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006189 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006190 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006191 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006192
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006193 /* If very first arg is "" or '', dest.data may end up NULL.
6194 * Preventing this: */
6195 o_addchr(&dest, '\0');
6196 dest.length = 0;
6197
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006198 G.ifs = get_local_var_value("IFS");
6199 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01006200 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006201
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006202 reset:
6203#if ENABLE_HUSH_INTERACTIVE
6204 input->promptmode = 0; /* PS1 */
6205#endif
6206 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6207 initialize_context(&ctx);
6208 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006209 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006210 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006211 const char *is_ifs;
6212 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006213 int ch;
6214 int next;
6215 int redir_fd;
6216 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006217
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006218 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006219 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006220 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006221 goto parse_error;
6222 }
6223 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006224 is_in_dquote = 0;
6225 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006226 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006227 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6228 ch, ch, dest.o_escape);
6229 if (ch == EOF) {
6230 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006231
6232 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006233 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006234 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006235 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006236 /* end_trigger == '}' case errors out earlier,
6237 * checking only ')' */
6238 if (end_trigger == ')') {
6239 syntax_error_unterm_ch('('); /* exits */
6240 /* goto parse_error; */
6241 }
6242
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006243 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006244 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006245 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006246 o_free(&dest);
6247 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006248 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006249 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006250 /* (this makes bare "&" cmd a no-op.
6251 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006252 if (pi->num_cmds == 0
6253 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6254 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006255 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006256 pi = NULL;
6257 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006258#if !BB_MMU
6259 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6260 if (pstring)
6261 *pstring = ctx.as_string.data;
6262 else
6263 o_free_unsafe(&ctx.as_string);
6264#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006265 debug_leave();
6266 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006267 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006268 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006269 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006270
6271 next = '\0';
6272 if (ch != '\n')
6273 next = i_peek(input);
6274
6275 is_special = "{}<>;&|()#'" /* special outside of "str" */
6276 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6277 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02006278 if (ctx.command->argv /* word [word]{... - non-special */
6279 || dest.length /* word{... - non-special */
6280 || dest.o_quoted /* ""{... - non-special */
6281 || (next != ';' /* }; - special */
6282 && next != ')' /* }) - special */
6283 && next != '&' /* }& and }&& ... - special */
6284 && next != '|' /* }|| ... - special */
6285 && !strchr(G.ifs, next) /* {word - non-special */
6286 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006287 ) {
6288 /* They are not special, skip "{}" */
6289 is_special += 2;
6290 }
6291 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006292 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006293
6294 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006295 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006296 o_addQchr(&dest, ch);
6297 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6298 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006299 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006300 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006301 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006302 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006303 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006304 continue;
6305 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006306
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006307 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006308 if (done_word(&dest, &ctx)) {
6309 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006310 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006311 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006312#if ENABLE_HUSH_CASE
6313 /* "case ... in <newline> word) ..." -
6314 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006315 if (ctx.command->argv == NULL
6316 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006317 ) {
6318 continue;
6319 }
6320#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006321 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006322 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006323 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6324 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006325 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006326 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006327 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006328 heredoc_cnt = 0;
6329 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006330 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006331 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006332 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006333 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006334 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006335 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006336
6337 /* "cmd}" or "cmd }..." without semicolon or &:
6338 * } is an ordinary char in this case, even inside { cmd; }
6339 * Pathological example: { ""}; } should exec "}" cmd
6340 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006341 if (ch == '}') {
6342 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6343 || dest.length != 0 /* word} */
6344 || dest.o_quoted /* ""} */
6345 ) {
6346 goto ordinary_char;
6347 }
6348 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6349 goto skip_end_trigger;
6350 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006351 }
6352
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006353 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006354 && (ch != ';' || heredoc_cnt == 0)
6355#if ENABLE_HUSH_CASE
6356 && (ch != ')'
6357 || ctx.ctx_res_w != RES_MATCH
6358 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6359 )
6360#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006361 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006362 if (heredoc_cnt) {
6363 /* This is technically valid:
6364 * { cat <<HERE; }; echo Ok
6365 * heredoc
6366 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006367 * HERE
6368 * but we don't support this.
6369 * We require heredoc to be in enclosing {}/(),
6370 * if any.
6371 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006372 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006373 goto parse_error;
6374 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006375 if (done_word(&dest, &ctx)) {
6376 goto parse_error;
6377 }
6378 done_pipe(&ctx, PIPE_SEQ);
6379 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006380 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006381 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006382 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006383 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006384 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006385#if !BB_MMU
6386 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6387 if (pstring)
6388 *pstring = ctx.as_string.data;
6389 else
6390 o_free_unsafe(&ctx.as_string);
6391#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006392 debug_leave();
6393 debug_printf_parse("parse_stream return %p: "
6394 "end_trigger char found\n",
6395 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006396 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006397 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006398 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006399 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006400 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006401 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006402
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006403 /* Catch <, > before deciding whether this word is
6404 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6405 switch (ch) {
6406 case '>':
6407 redir_fd = redirect_opt_num(&dest);
6408 if (done_word(&dest, &ctx)) {
6409 goto parse_error;
6410 }
6411 redir_style = REDIRECT_OVERWRITE;
6412 if (next == '>') {
6413 redir_style = REDIRECT_APPEND;
6414 ch = i_getch(input);
6415 nommu_addchr(&ctx.as_string, ch);
6416 }
6417#if 0
6418 else if (next == '(') {
6419 syntax_error(">(process) not supported");
6420 goto parse_error;
6421 }
6422#endif
6423 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6424 goto parse_error;
6425 continue; /* back to top of while (1) */
6426 case '<':
6427 redir_fd = redirect_opt_num(&dest);
6428 if (done_word(&dest, &ctx)) {
6429 goto parse_error;
6430 }
6431 redir_style = REDIRECT_INPUT;
6432 if (next == '<') {
6433 redir_style = REDIRECT_HEREDOC;
6434 heredoc_cnt++;
6435 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6436 ch = i_getch(input);
6437 nommu_addchr(&ctx.as_string, ch);
6438 } else if (next == '>') {
6439 redir_style = REDIRECT_IO;
6440 ch = i_getch(input);
6441 nommu_addchr(&ctx.as_string, ch);
6442 }
6443#if 0
6444 else if (next == '(') {
6445 syntax_error("<(process) not supported");
6446 goto parse_error;
6447 }
6448#endif
6449 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6450 goto parse_error;
6451 continue; /* back to top of while (1) */
6452 }
6453
6454 if (dest.o_assignment == MAYBE_ASSIGNMENT
6455 /* check that we are not in word in "a=1 2>word b=1": */
6456 && !ctx.pending_redirect
6457 ) {
6458 /* ch is a special char and thus this word
6459 * cannot be an assignment */
6460 dest.o_assignment = NOT_ASSIGNMENT;
6461 }
6462
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006463 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6464
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006465 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006466 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006467 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006468 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006469 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006470 if (ch == EOF || ch == '\n')
6471 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006472 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006473 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006474 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006475 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006476 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006477 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006478 }
6479 break;
6480 case '\\':
6481 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006482 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006483 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006484 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006485 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006486 if (ch != '\n') {
6487 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006488 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006489 o_addchr(&dest, ch);
6490 nommu_addchr(&ctx.as_string, ch);
6491 /* Example: echo Hello \2>file
6492 * we need to know that word 2 is quoted */
6493 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006494 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006495#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006496 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006497 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6498 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006499 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006500#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006501 break;
6502 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006503 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006504 debug_printf_parse("parse_stream parse error: "
6505 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006506 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006507 }
Eric Andersen25f27032001-04-26 23:22:31 +00006508 break;
6509 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006510 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006511 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006512 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006513 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006514 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006515 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006516 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006517 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006518 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006519 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006520 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006521 }
Eric Andersen25f27032001-04-26 23:22:31 +00006522 break;
6523 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006524 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006525 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006526 if (dest.o_assignment == NOT_ASSIGNMENT)
6527 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006528 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006529#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006530 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006531#if !BB_MMU
6532 int pos;
6533#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006534 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6535 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006536#if !BB_MMU
6537 pos = dest.length;
6538#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006539 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006540#if !BB_MMU
6541 o_addstr(&ctx.as_string, dest.data + pos);
6542 o_addchr(&ctx.as_string, '`');
6543#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006544 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6545 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006546 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006547 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006548#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006549 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006550#if ENABLE_HUSH_CASE
6551 case_semi:
6552#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006553 if (done_word(&dest, &ctx)) {
6554 goto parse_error;
6555 }
6556 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006557#if ENABLE_HUSH_CASE
6558 /* Eat multiple semicolons, detect
6559 * whether it means something special */
6560 while (1) {
6561 ch = i_peek(input);
6562 if (ch != ';')
6563 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006564 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006565 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006566 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006567 ctx.ctx_dsemicolon = 1;
6568 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006569 break;
6570 }
6571 }
6572#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006573 new_cmd:
6574 /* We just finished a cmd. New one may start
6575 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006576 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006577 break;
6578 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006579 if (done_word(&dest, &ctx)) {
6580 goto parse_error;
6581 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006582 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006583 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006584 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006585 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006586 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006587 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006588 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006589 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006590 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006591 if (done_word(&dest, &ctx)) {
6592 goto parse_error;
6593 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006594#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006595 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006596 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006597#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006598 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006599 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006600 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006601 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006602 } else {
6603 /* we could pick up a file descriptor choice here
6604 * with redirect_opt_num(), but bash doesn't do it.
6605 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006606 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006607#if !BB_MMU
6608 o_reset_to_empty_unquoted(&ctx.as_string);
6609#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006610 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006611 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006612 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006613#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006614 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006615 if (ctx.ctx_res_w == RES_MATCH
6616 && ctx.command->argv == NULL /* not (word|(... */
6617 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006618 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006619 ) {
6620 continue;
6621 }
6622#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006623 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006624 if (parse_group(&dest, &ctx, input, ch) != 0) {
6625 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006626 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006627 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006628 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006629#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006630 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006631 goto case_semi;
6632#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006633 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006634 /* proper use of this character is caught by end_trigger:
6635 * if we see {, we call parse_group(..., end_trigger='}')
6636 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006637 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006638 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006639 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006640 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006641 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006642 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006643 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006644
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006645 parse_error:
6646 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006647 struct parse_context *pctx;
6648 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006649
6650 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006651 * Sample for finding leaks on syntax error recovery path.
6652 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006653 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006654 * Samples to catch leaks at execution:
6655 * while if (true | {true;}); then echo ok; fi; do break; done
6656 * 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 +00006657 */
6658 pctx = &ctx;
6659 do {
6660 /* Update pipe/command counts,
6661 * otherwise freeing may miss some */
6662 done_pipe(pctx, PIPE_SEQ);
6663 debug_printf_clean("freeing list %p from ctx %p\n",
6664 pctx->list_head, pctx);
6665 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006666 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006667 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006668#if !BB_MMU
6669 o_free_unsafe(&pctx->as_string);
6670#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006671 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006672 if (pctx != &ctx) {
6673 free(pctx);
6674 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006675 IF_HAS_KEYWORDS(pctx = p2;)
6676 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006677 /* Free text, clear all dest fields */
6678 o_free(&dest);
6679 /* If we are not in top-level parse, we return,
6680 * our caller will propagate error.
6681 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006682 if (end_trigger != ';') {
6683#if !BB_MMU
6684 if (pstring)
6685 *pstring = NULL;
6686#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006687 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006688 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006689 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006690 /* Discard cached input, force prompt */
6691 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006692 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006693 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006694 }
Eric Andersen25f27032001-04-26 23:22:31 +00006695}
6696
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006697/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006698 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6699 * end_trigger controls how often we stop parsing
6700 * NUL: parse all, execute, return
6701 * ';': parse till ';' or newline, execute, repeat till EOF
6702 */
6703static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006704{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006705 /* Why we need empty flag?
6706 * An obscure corner case "false; ``; echo $?":
6707 * empty command in `` should still set $? to 0.
6708 * But we can't just set $? to 0 at the start,
6709 * this breaks "false; echo `echo $?`" case.
6710 */
6711 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006712 while (1) {
6713 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006714
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006715 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006716 if (!pipe_list) { /* EOF */
6717 if (empty)
6718 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006719 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006720 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006721 debug_print_tree(pipe_list, 0);
6722 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6723 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006724 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006725 }
Eric Andersen25f27032001-04-26 23:22:31 +00006726}
6727
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006728static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006729{
6730 struct in_str input;
6731 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006732 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006733}
6734
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006735static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006736{
Eric Andersen25f27032001-04-26 23:22:31 +00006737 struct in_str input;
6738 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006739 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006740}
6741
Denis Vlasenkof9375282009-04-05 19:13:39 +00006742/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006743static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006744{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006745 unsigned sig;
6746 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006747 sigset_t old_blocked_set;
6748
6749 if (!G.inherited_set_is_saved) {
6750 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6751 G.inherited_set = G.blocked_set;
6752 }
6753 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006754
Denis Vlasenkof9375282009-04-05 19:13:39 +00006755 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006756 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006757 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006758 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006759 mask |= SPECIAL_JOB_SIGS;
6760 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006761 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006762
Denis Vlasenkof9375282009-04-05 19:13:39 +00006763 sig = 0;
6764 while (mask) {
6765 if (mask & 1)
6766 sigaddset(&G.blocked_set, sig);
6767 mask >>= 1;
6768 sig++;
6769 }
6770 sigdelset(&G.blocked_set, SIGCHLD);
6771
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006772 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
6773 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6774
Denis Vlasenkof9375282009-04-05 19:13:39 +00006775 /* POSIX allows shell to re-enable SIGCHLD
6776 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006777#if ENABLE_HUSH_FAST
6778 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006779 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006780 signal(SIGCHLD, SIGCHLD_handler);
6781#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006782 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006783 signal(SIGCHLD, SIG_DFL);
6784#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006785
6786 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00006787}
6788
6789#if ENABLE_HUSH_JOB
6790/* helper */
6791static void maybe_set_to_sigexit(int sig)
6792{
6793 void (*handler)(int);
6794 /* non_DFL_mask'ed signals are, well, masked,
6795 * no need to set handler for them.
6796 */
6797 if (!((G.non_DFL_mask >> sig) & 1)) {
6798 handler = signal(sig, sigexit);
6799 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6800 signal(sig, handler);
6801 }
6802}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006803/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006804static void set_fatal_handlers(void)
6805{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006806 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006807 if (HUSH_DEBUG) {
6808 maybe_set_to_sigexit(SIGILL );
6809 maybe_set_to_sigexit(SIGFPE );
6810 maybe_set_to_sigexit(SIGBUS );
6811 maybe_set_to_sigexit(SIGSEGV);
6812 maybe_set_to_sigexit(SIGTRAP);
6813 } /* else: hush is perfect. what SEGV? */
6814 maybe_set_to_sigexit(SIGABRT);
6815 /* bash 3.2 seems to handle these just like 'fatal' ones */
6816 maybe_set_to_sigexit(SIGPIPE);
6817 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006818 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006819 * if we aren't interactive... but in this case
6820 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006821 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006822 /*maybe_set_to_sigexit(SIGTERM);*/
6823 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006824}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006825#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006826
Denis Vlasenkod5762932009-03-31 11:22:57 +00006827static int set_mode(const char cstate, const char mode)
6828{
6829 int state = (cstate == '-' ? 1 : 0);
6830 switch (mode) {
6831 case 'n': G.fake_mode = state; break;
6832 case 'x': /*G.debug_mode = state;*/ break;
6833 default: return EXIT_FAILURE;
6834 }
6835 return EXIT_SUCCESS;
6836}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006837
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006838int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006839int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006840{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006841 static const struct variable const_shell_ver = {
6842 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006843 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006844 .max_len = 1, /* 0 can provoke free(name) */
6845 .flg_export = 1,
6846 .flg_read_only = 1,
6847 };
Eric Andersen25f27032001-04-26 23:22:31 +00006848 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006849 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006850 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006851 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006852
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006853 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02006854 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006855 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006856#if !BB_MMU
6857 G.argv0_for_re_execing = argv[0];
6858#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006859 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006860 G.shell_ver = const_shell_ver; /* copying struct here */
6861 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006862 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006863 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6864 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006865 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006866 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006867 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006868 if (e) while (*e) {
6869 char *value = strchr(*e, '=');
6870 if (value) { /* paranoia */
6871 cur_var->next = xzalloc(sizeof(*cur_var));
6872 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006873 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006874 cur_var->max_len = strlen(*e);
6875 cur_var->flg_export = 1;
6876 }
6877 e++;
6878 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006879 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006880 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02006881 putenv((char *)hush_version_str);
6882
6883 /* Export PWD */
6884 set_pwd_var(/*exp:*/ 1);
6885 /* bash also exports SHLVL and _,
6886 * and sets (but doesn't export) the following variables:
6887 * BASH=/bin/bash
6888 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6889 * BASH_VERSION='3.2.0(1)-release'
6890 * HOSTTYPE=i386
6891 * MACHTYPE=i386-pc-linux-gnu
6892 * OSTYPE=linux-gnu
6893 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02006894 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02006895 * EUID=<NNNNN>
6896 * UID=<NNNNN>
6897 * GROUPS=()
6898 * LINES=<NNN>
6899 * COLUMNS=<NNN>
6900 * BASH_ARGC=()
6901 * BASH_ARGV=()
6902 * BASH_LINENO=()
6903 * BASH_SOURCE=()
6904 * DIRSTACK=()
6905 * PIPESTATUS=([0]="0")
6906 * HISTFILE=/<xxx>/.bash_history
6907 * HISTFILESIZE=500
6908 * HISTSIZE=500
6909 * MAILCHECK=60
6910 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6911 * SHELL=/bin/bash
6912 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6913 * TERM=dumb
6914 * OPTERR=1
6915 * OPTIND=1
6916 * IFS=$' \t\n'
6917 * PS1='\s-\v\$ '
6918 * PS2='> '
6919 * PS4='+ '
6920 */
6921
Denis Vlasenko38f63192007-01-22 09:03:07 +00006922#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006923 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006924#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006925 G.global_argc = argc;
6926 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006927 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006928 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006929
Denis Vlasenkoed782372009-04-10 00:45:02 +00006930 if (setjmp(die_jmp)) {
6931 /* xfunc has failed! die die die */
6932 /* no EXIT traps, this is an escape hatch! */
6933 G.exiting = 1;
6934 hush_exit(xfunc_error_retval);
6935 }
6936
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006937 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006938 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006939 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006940 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006941 * in order to intercept (more) signals.
6942 */
6943
6944 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006945 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006946 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006947 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02006948 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006949#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006950 "<:$:R:V:"
6951# if ENABLE_HUSH_FUNCTIONS
6952 "F:"
6953# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006954#endif
6955 );
6956 if (opt <= 0)
6957 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006958 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006959 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006960 /* Possibilities:
6961 * sh ... -c 'script'
6962 * sh ... -c 'script' ARG0 [ARG1...]
6963 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01006964 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006965 * "" needs to be replaced with NULL
6966 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01006967 * Note: the form without ARG0 never happens:
6968 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006969 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02006970 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006971 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02006972 G.root_ppid = getppid();
6973 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006974 G.global_argv = argv + optind;
6975 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006976 if (builtin_argc) {
6977 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6978 const struct built_in_command *x;
6979
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006980 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006981 x = find_builtin(optarg);
6982 if (x) { /* paranoia */
6983 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6984 G.global_argv += builtin_argc;
6985 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01006986 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006987 }
6988 goto final_return;
6989 }
6990 if (!G.global_argv[0]) {
6991 /* -c 'script' (no params): prevent empty $0 */
6992 G.global_argv--; /* points to argv[i] of 'script' */
6993 G.global_argv[0] = argv[0];
6994 G.global_argc--;
6995 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006996 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006997 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006998 goto final_return;
6999 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007000 /* Well, we cannot just declare interactiveness,
7001 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007002 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007003 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007004 case 's':
7005 /* "-s" means "read from stdin", but this is how we always
7006 * operate, so simply do nothing here. */
7007 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007008#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007009 case '<': /* "big heredoc" support */
7010 full_write(STDOUT_FILENO, optarg, strlen(optarg));
7011 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007012 case '$': {
7013 unsigned long long empty_trap_mask;
7014
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007015 G.root_pid = bb_strtou(optarg, &optarg, 16);
7016 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007017 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7018 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007019 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7020 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007021 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007022 optarg++;
7023 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007024 optarg++;
7025 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7026 if (empty_trap_mask != 0) {
7027 int sig;
7028 init_sigmasks();
7029 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7030 for (sig = 1; sig < NSIG; sig++) {
7031 if (empty_trap_mask & (1LL << sig)) {
7032 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7033 sigaddset(&G.blocked_set, sig);
7034 }
7035 }
7036 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7037 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007038# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007039 optarg++;
7040 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007041# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007042 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007043 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007044 case 'R':
7045 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007046 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007047 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007048# if ENABLE_HUSH_FUNCTIONS
7049 case 'F': {
7050 struct function *funcp = new_function(optarg);
7051 /* funcp->name is already set to optarg */
7052 /* funcp->body is set to NULL. It's a special case. */
7053 funcp->body_as_string = argv[optind];
7054 optind++;
7055 break;
7056 }
7057# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007058#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007059 case 'n':
7060 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00007061 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007062 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007063 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007064#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007065 fprintf(stderr, "Usage: sh [FILE]...\n"
7066 " or: sh -c command [args]...\n\n");
7067 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007068#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007069 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007070#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007071 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007072 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007073
Denys Vlasenkodea47882009-10-09 15:40:49 +02007074 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007075 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007076 G.root_ppid = getppid();
7077 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007078
7079 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007080 if (argv[0] && argv[0][0] == '-') {
7081 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007082 debug_printf("sourcing /etc/profile\n");
7083 input = fopen_for_read("/etc/profile");
7084 if (input != NULL) {
7085 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007086 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007087 parse_and_run_file(input);
7088 fclose(input);
7089 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007090 /* bash: after sourcing /etc/profile,
7091 * tries to source (in the given order):
7092 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007093 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007094 * bash also sources ~/.bash_logout on exit.
7095 * If called as sh, skips .bash_XXX files.
7096 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007097 }
7098
Denis Vlasenkof9375282009-04-05 19:13:39 +00007099 if (argv[optind]) {
7100 FILE *input;
7101 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007102 * "bash <script>" (which is never interactive (unless -i?))
7103 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007104 * If called as sh, does the same but with $ENV.
7105 */
7106 debug_printf("running script '%s'\n", argv[optind]);
7107 G.global_argv = argv + optind;
7108 G.global_argc = argc - optind;
7109 input = xfopen_for_read(argv[optind]);
7110 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007111 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007112 parse_and_run_file(input);
7113#if ENABLE_FEATURE_CLEAN_UP
7114 fclose(input);
7115#endif
7116 goto final_return;
7117 }
7118
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007119 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007120 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007121 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007122
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007123 /* A shell is interactive if the '-i' flag was given,
7124 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007125 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007126 * no arguments remaining or the -s flag given
7127 * standard input is a terminal
7128 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007129 * Refer to Posix.2, the description of the 'sh' utility.
7130 */
7131#if ENABLE_HUSH_JOB
7132 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007133 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7134 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7135 if (G_saved_tty_pgrp < 0)
7136 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007137
7138 /* try to dup stdin to high fd#, >= 255 */
7139 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7140 if (G_interactive_fd < 0) {
7141 /* try to dup to any fd */
7142 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007143 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007144 /* give up */
7145 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007146 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007147 }
7148 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007149// TODO: track & disallow any attempts of user
7150// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007151 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007152 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007153 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007154 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007155
Mike Frysinger38478a62009-05-20 04:48:06 -04007156 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007157 /* If we were run as 'hush &', sleep until we are
7158 * in the foreground (tty pgrp == our pgrp).
7159 * If we get started under a job aware app (like bash),
7160 * make sure we are now in charge so we don't fight over
7161 * who gets the foreground */
7162 while (1) {
7163 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007164 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7165 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007166 break;
7167 /* send TTIN to ourself (should stop us) */
7168 kill(- shell_pgrp, SIGTTIN);
7169 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007170 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007171
Denis Vlasenkof9375282009-04-05 19:13:39 +00007172 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007173 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007174
Mike Frysinger38478a62009-05-20 04:48:06 -04007175 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007176 /* Set other signals to restore saved_tty_pgrp */
7177 set_fatal_handlers();
7178 /* Put ourselves in our own process group
7179 * (bash, too, does this only if ctty is available) */
7180 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7181 /* Grab control of the terminal */
7182 tcsetpgrp(G_interactive_fd, getpid());
7183 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007184 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007185 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007186 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007187 } else {
7188 init_sigmasks();
7189 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007190#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007191 /* No job control compiled in, only prompt/line editing */
7192 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007193 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7194 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007195 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007196 G_interactive_fd = dup(STDIN_FILENO);
7197 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007198 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007199 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007200 }
7201 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007202 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007203 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007204 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007205 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007206#else
7207 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007208 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007209#endif
7210 /* bash:
7211 * if interactive but not a login shell, sources ~/.bashrc
7212 * (--norc turns this off, --rcfile <file> overrides)
7213 */
7214
7215 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007216 /* note: ash and hush share this string */
7217 printf("\n\n%s %s\n"
7218 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7219 "\n",
7220 bb_banner,
7221 "hush - the humble shell"
7222 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007223 }
7224
Denis Vlasenkof9375282009-04-05 19:13:39 +00007225 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007226
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007227 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007228#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007229 if (G.cwd != bb_msg_unknown)
7230 free((char*)G.cwd);
7231 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007232 while (cur_var) {
7233 struct variable *tmp = cur_var;
7234 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007235 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007236 cur_var = cur_var->next;
7237 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007238 }
Eric Andersen25f27032001-04-26 23:22:31 +00007239#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007240 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007241}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007242
7243
7244#if ENABLE_LASH
7245int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7246int lash_main(int argc, char **argv)
7247{
Denys Vlasenko07934912009-08-20 03:40:04 +02007248 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007249 return hush_main(argc, argv);
7250}
7251#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007252
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007253#if ENABLE_MSH
7254int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7255int msh_main(int argc, char **argv)
7256{
7257 //bb_error_msg("msh is deprecated, please use hush instead");
7258 return hush_main(argc, argv);
7259}
7260#endif
7261
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007262
7263/*
7264 * Built-ins
7265 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007266static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007267{
7268 return 0;
7269}
7270
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007271static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007272{
7273 int argc = 0;
7274 while (*argv) {
7275 argc++;
7276 argv++;
7277 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007278 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007279}
7280
7281static int FAST_FUNC builtin_test(char **argv)
7282{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007283 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007284}
7285
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007286static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007287{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007288 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007289}
7290
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007291#if ENABLE_PRINTF
7292static int FAST_FUNC builtin_printf(char **argv)
7293{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007294 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007295}
7296#endif
7297
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007298static char **skip_dash_dash(char **argv)
7299{
7300 argv++;
7301 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7302 argv++;
7303 return argv;
7304}
7305
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007306static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007307{
7308 int rcode = EXIT_SUCCESS;
7309
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007310 argv = skip_dash_dash(argv);
7311 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007312 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007313 /* bash:
7314 * eval "echo Hi; done" ("done" is syntax error):
7315 * "echo Hi" will not execute too.
7316 */
7317 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007318 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007319 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007320 }
7321 return rcode;
7322}
7323
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007324static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007325{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007326 const char *newdir;
7327
7328 argv = skip_dash_dash(argv);
7329 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007330 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007331 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007332 * bash says "bash: cd: HOME not set" and does nothing
7333 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007334 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007335 const char *home = get_local_var_value("HOME");
7336 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007337 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007338 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007339 /* Mimic bash message exactly */
7340 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007341 return EXIT_FAILURE;
7342 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007343 /* Read current dir (get_cwd(1) is inside) and set PWD.
7344 * Note: do not enforce exporting. If PWD was unset or unexported,
7345 * set it again, but do not export. bash does the same.
7346 */
7347 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007348 return EXIT_SUCCESS;
7349}
7350
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007351static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007352{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007353 argv = skip_dash_dash(argv);
7354 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007355 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007356
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007357 /* Careful: we can end up here after [v]fork. Do not restore
7358 * tty pgrp then, only top-level shell process does that */
7359 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7360 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7361
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007362 /* TODO: if exec fails, bash does NOT exit! We do.
7363 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7364 * and tcsetpgrp, and this is inherently racy.
7365 */
7366 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007367}
7368
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007369static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007370{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007371 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007372
7373 /* interactive bash:
7374 * # trap "echo EEE" EXIT
7375 * # exit
7376 * exit
7377 * There are stopped jobs.
7378 * (if there are _stopped_ jobs, running ones don't count)
7379 * # exit
7380 * exit
7381 # EEE (then bash exits)
7382 *
7383 * we can use G.exiting = -1 as indicator "last cmd was exit"
7384 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007385
7386 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007387 argv = skip_dash_dash(argv);
7388 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007389 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007390 /* mimic bash: exit 123abc == exit 255 + error msg */
7391 xfunc_error_retval = 255;
7392 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007393 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007394}
7395
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007396static void print_escaped(const char *s)
7397{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007398 if (*s == '\'')
7399 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007400 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007401 const char *p = strchrnul(s, '\'');
7402 /* print 'xxxx', possibly just '' */
7403 printf("'%.*s'", (int)(p - s), s);
7404 if (*p == '\0')
7405 break;
7406 s = p;
7407 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007408 /* s points to '; print "'''...'''" */
7409 putchar('"');
7410 do putchar('\''); while (*++s == '\'');
7411 putchar('"');
7412 } while (*s);
7413}
7414
Denys Vlasenko295fef82009-06-03 12:47:26 +02007415#if !ENABLE_HUSH_LOCAL
7416#define helper_export_local(argv, exp, lvl) \
7417 helper_export_local(argv, exp)
7418#endif
7419static void helper_export_local(char **argv, int exp, int lvl)
7420{
7421 do {
7422 char *name = *argv;
7423
7424 /* So far we do not check that name is valid (TODO?) */
7425
7426 if (strchr(name, '=') == NULL) {
7427 struct variable *var;
7428
7429 var = get_local_var(name);
7430 if (exp == -1) { /* unexporting? */
7431 /* export -n NAME (without =VALUE) */
7432 if (var) {
7433 var->flg_export = 0;
7434 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7435 unsetenv(name);
7436 } /* else: export -n NOT_EXISTING_VAR: no-op */
7437 continue;
7438 }
7439 if (exp == 1) { /* exporting? */
7440 /* export NAME (without =VALUE) */
7441 if (var) {
7442 var->flg_export = 1;
7443 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7444 putenv(var->varstr);
7445 continue;
7446 }
7447 }
7448 /* Exporting non-existing variable.
7449 * bash does not put it in environment,
7450 * but remembers that it is exported,
7451 * and does put it in env when it is set later.
7452 * We just set it to "" and export. */
7453 /* Or, it's "local NAME" (without =VALUE).
7454 * bash sets the value to "". */
7455 name = xasprintf("%s=", name);
7456 } else {
7457 /* (Un)exporting/making local NAME=VALUE */
7458 name = xstrdup(name);
7459 }
7460 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7461 } while (*++argv);
7462}
7463
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007464static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007465{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007466 unsigned opt_unexport;
7467
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007468#if ENABLE_HUSH_EXPORT_N
7469 /* "!": do not abort on errors */
7470 opt_unexport = getopt32(argv, "!n");
7471 if (opt_unexport == (uint32_t)-1)
7472 return EXIT_FAILURE;
7473 argv += optind;
7474#else
7475 opt_unexport = 0;
7476 argv++;
7477#endif
7478
7479 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007480 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007481 if (e) {
7482 while (*e) {
7483#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007484 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007485#else
7486 /* ash emits: export VAR='VAL'
7487 * bash: declare -x VAR="VAL"
7488 * we follow ash example */
7489 const char *s = *e++;
7490 const char *p = strchr(s, '=');
7491
7492 if (!p) /* wtf? take next variable */
7493 continue;
7494 /* export var= */
7495 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007496 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007497 putchar('\n');
7498#endif
7499 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007500 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007501 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007502 return EXIT_SUCCESS;
7503 }
7504
Denys Vlasenko295fef82009-06-03 12:47:26 +02007505 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007506
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007507 return EXIT_SUCCESS;
7508}
7509
Denys Vlasenko295fef82009-06-03 12:47:26 +02007510#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007511static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007512{
7513 if (G.func_nest_level == 0) {
7514 bb_error_msg("%s: not in a function", argv[0]);
7515 return EXIT_FAILURE; /* bash compat */
7516 }
7517 helper_export_local(argv, 0, G.func_nest_level);
7518 return EXIT_SUCCESS;
7519}
7520#endif
7521
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007522static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007523{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007524 int sig;
7525 char *new_cmd;
7526
7527 if (!G.traps)
7528 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7529
7530 argv++;
7531 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007532 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007533 /* No args: print all trapped */
7534 for (i = 0; i < NSIG; ++i) {
7535 if (G.traps[i]) {
7536 printf("trap -- ");
7537 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007538 /* note: bash adds "SIG", but only if invoked
7539 * as "bash". If called as "sh", or if set -o posix,
7540 * then it prints short signal names.
7541 * We are printing short names: */
7542 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007543 }
7544 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007545 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007546 return EXIT_SUCCESS;
7547 }
7548
7549 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007550 /* If first arg is a number: reset all specified signals */
7551 sig = bb_strtou(*argv, NULL, 10);
7552 if (errno == 0) {
7553 int ret;
7554 process_sig_list:
7555 ret = EXIT_SUCCESS;
7556 while (*argv) {
7557 sig = get_signum(*argv++);
7558 if (sig < 0 || sig >= NSIG) {
7559 ret = EXIT_FAILURE;
7560 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007561 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007562 continue;
7563 }
7564
7565 free(G.traps[sig]);
7566 G.traps[sig] = xstrdup(new_cmd);
7567
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007568 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007569 get_signame(sig), sig, G.traps[sig]);
7570
7571 /* There is no signal for 0 (EXIT) */
7572 if (sig == 0)
7573 continue;
7574
7575 if (new_cmd) {
7576 sigaddset(&G.blocked_set, sig);
7577 } else {
7578 /* There was a trap handler, we are removing it
7579 * (if sig has non-DFL handling,
7580 * we don't need to do anything) */
7581 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7582 continue;
7583 sigdelset(&G.blocked_set, sig);
7584 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007585 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007586 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007587 return ret;
7588 }
7589
7590 if (!argv[1]) { /* no second arg */
7591 bb_error_msg("trap: invalid arguments");
7592 return EXIT_FAILURE;
7593 }
7594
7595 /* First arg is "-": reset all specified to default */
7596 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7597 /* Everything else: set arg as signal handler
7598 * (includes "" case, which ignores signal) */
7599 if (argv[0][0] == '-') {
7600 if (argv[0][1] == '\0') { /* "-" */
7601 /* new_cmd remains NULL: "reset these sigs" */
7602 goto reset_traps;
7603 }
7604 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7605 argv++;
7606 }
7607 /* else: "-something", no special meaning */
7608 }
7609 new_cmd = *argv;
7610 reset_traps:
7611 argv++;
7612 goto process_sig_list;
7613}
7614
Mike Frysinger93cadc22009-05-27 17:06:25 -04007615/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007616static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007617{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007618 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007619
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007620 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007621 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007622 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007623
7624 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007625 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007626 type = "an alias";*/
7627#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007628 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007629 type = "a function";
7630#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007631 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007632 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007633 else if ((path = find_in_path(*argv)) != NULL)
7634 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007635 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007636 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007637 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007638 continue;
7639 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007640
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007641 printf("%s is %s\n", *argv, type);
7642 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007643 }
7644
7645 return ret;
7646}
7647
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007648#if ENABLE_HUSH_JOB
7649/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007650static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007651{
7652 int i, jobnum;
7653 struct pipe *pi;
7654
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007655 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007656 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007657
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007658 /* If they gave us no args, assume they want the last backgrounded task */
7659 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007660 for (pi = G.job_list; pi; pi = pi->next) {
7661 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007662 goto found;
7663 }
7664 }
7665 bb_error_msg("%s: no current job", argv[0]);
7666 return EXIT_FAILURE;
7667 }
7668 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7669 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7670 return EXIT_FAILURE;
7671 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007672 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007673 if (pi->jobid == jobnum) {
7674 goto found;
7675 }
7676 }
7677 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7678 return EXIT_FAILURE;
7679 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007680 /* TODO: bash prints a string representation
7681 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007682 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007683 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007684 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007685 }
7686
7687 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007688 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7689 for (i = 0; i < pi->num_cmds; i++) {
7690 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7691 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007692 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007693 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007694
7695 i = kill(- pi->pgrp, SIGCONT);
7696 if (i < 0) {
7697 if (errno == ESRCH) {
7698 delete_finished_bg_job(pi);
7699 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007700 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007701 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007702 }
7703
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007704 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007705 remove_bg_job(pi);
7706 return checkjobs_and_fg_shell(pi);
7707 }
7708 return EXIT_SUCCESS;
7709}
7710#endif
7711
7712#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007713static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007714{
7715 const struct built_in_command *x;
7716
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007717 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007718 "Built-in commands:\n"
7719 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007720 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01007721 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007722 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007723 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007724 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007725 return EXIT_SUCCESS;
7726}
7727#endif
7728
7729#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007730static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007731{
7732 struct pipe *job;
7733 const char *status_string;
7734
Denis Vlasenko87a86552008-07-29 19:43:10 +00007735 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007736 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007737 status_string = "Stopped";
7738 else
7739 status_string = "Running";
7740
7741 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7742 }
7743 return EXIT_SUCCESS;
7744}
7745#endif
7746
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007747#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007748static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007749{
7750 void *p;
7751 unsigned long l;
7752
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007753# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02007754 /* Optional. Reduces probability of false positives */
7755 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007756# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007757 /* Crude attempt to find where "free memory" starts,
7758 * sans fragmentation. */
7759 p = malloc(240);
7760 l = (unsigned long)p;
7761 free(p);
7762 p = malloc(3400);
7763 if (l < (unsigned long)p) l = (unsigned long)p;
7764 free(p);
7765
7766 if (!G.memleak_value)
7767 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007768
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007769 l -= G.memleak_value;
7770 if ((long)l < 0)
7771 l = 0;
7772 l /= 1024;
7773 if (l > 127)
7774 l = 127;
7775
7776 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7777 return l;
7778}
7779#endif
7780
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007781static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007782{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007783 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007784 return EXIT_SUCCESS;
7785}
7786
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007787static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007788{
Denys Vlasenko03dad222010-01-12 23:29:57 +01007789 const char *r;
7790 char *opt_n = NULL;
7791 char *opt_p = NULL;
7792 char *opt_t = NULL;
7793 char *opt_u = NULL;
7794 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007795
Denys Vlasenko03dad222010-01-12 23:29:57 +01007796 /* "!": do not abort on errors.
7797 * Option string must start with "sr" to match BUILTIN_READ_xxx
7798 */
7799 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
7800 if (read_flags == (uint32_t)-1)
7801 return EXIT_FAILURE;
7802 argv += optind;
7803
7804 r = shell_builtin_read(set_local_var_from_halves,
7805 argv,
7806 get_local_var_value("IFS"), /* can be NULL */
7807 read_flags,
7808 opt_n,
7809 opt_p,
7810 opt_t,
7811 opt_u
7812 );
7813
7814 if ((uintptr_t)r > 1) {
7815 bb_error_msg("%s", r);
7816 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007817 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007818
Denys Vlasenko03dad222010-01-12 23:29:57 +01007819 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007820}
7821
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007822/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7823 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007824 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007825 * set [-abCefhmnuvx] [-o option] [argument...]
7826 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007827 * set -- [argument...]
7828 * set -o
7829 * set +o
7830 * Implementations shall support the options in both their hyphen and
7831 * plus-sign forms. These options can also be specified as options to sh.
7832 * Examples:
7833 * Write out all variables and their values: set
7834 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7835 * Turn on the -x and -v options: set -xv
7836 * Unset all positional parameters: set --
7837 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7838 * Set the positional parameters to the expansion of x, even if x expands
7839 * with a leading '-' or '+': set -- $x
7840 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007841 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007842 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007843static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007844{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007845 int n;
7846 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007847 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007848
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007849 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007850 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007851 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007852 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007853 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007854 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007855
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007856 do {
7857 if (!strcmp(arg, "--")) {
7858 ++argv;
7859 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007860 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00007861 if (arg[0] != '+' && arg[0] != '-')
7862 break;
7863 for (n = 1; arg[n]; ++n)
7864 if (set_mode(arg[0], arg[n]))
7865 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007866 } while ((arg = *++argv) != NULL);
7867 /* Now argv[0] is 1st argument */
7868
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007869 if (arg == NULL)
7870 return EXIT_SUCCESS;
7871 set_argv:
7872
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007873 /* NB: G.global_argv[0] ($0) is never freed/changed */
7874 g_argv = G.global_argv;
7875 if (G.global_args_malloced) {
7876 pp = g_argv;
7877 while (*++pp)
7878 free(*pp);
7879 g_argv[1] = NULL;
7880 } else {
7881 G.global_args_malloced = 1;
7882 pp = xzalloc(sizeof(pp[0]) * 2);
7883 pp[0] = g_argv[0]; /* retain $0 */
7884 g_argv = pp;
7885 }
7886 /* This realloc's G.global_argv */
7887 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7888
7889 n = 1;
7890 while (*++pp)
7891 n++;
7892 G.global_argc = n;
7893
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007894 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007895
7896 /* Nothing known, so abort */
7897 error:
7898 bb_error_msg("set: %s: invalid option", arg);
7899 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007900}
7901
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007902static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007903{
7904 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007905 argv = skip_dash_dash(argv);
7906 if (argv[0]) {
7907 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007908 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007909 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007910 if (G.global_args_malloced) {
7911 int m = 1;
7912 while (m <= n)
7913 free(G.global_argv[m++]);
7914 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007915 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007916 memmove(&G.global_argv[1], &G.global_argv[n+1],
7917 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007918 return EXIT_SUCCESS;
7919 }
7920 return EXIT_FAILURE;
7921}
7922
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007923static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007924{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02007925 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007926 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007927 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007928#if ENABLE_HUSH_FUNCTIONS
7929 smallint sv_flg;
7930#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007931
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007932 argv = skip_dash_dash(argv);
7933 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02007934 if (!filename) {
7935 /* bash says: "bash: .: filename argument required" */
7936 return 2; /* bash compat */
7937 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007938 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02007939 if (!strchr(filename, '/')) {
7940 arg_path = find_in_path(filename);
7941 if (arg_path)
7942 filename = arg_path;
7943 }
7944 input = fopen_or_warn(filename, "r");
7945 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007946 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007947 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007948 return EXIT_FAILURE;
7949 }
7950 close_on_exec_on(fileno(input));
7951
Mike Frysinger885b6f22009-04-18 21:04:25 +00007952#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007953 sv_flg = G.flag_return_in_progress;
7954 /* "we are inside sourced file, ok to use return" */
7955 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007956#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007957 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007958
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007959 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007960 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007961
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007962 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00007963#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007964 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007965#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007966
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007967 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007968}
7969
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007970static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007971{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007972 int rc;
7973 mode_t mask;
7974
7975 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007976 argv = skip_dash_dash(argv);
7977 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007978 mode_t old_mask = mask;
7979
7980 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007981 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007982 mask ^= 0777;
7983 if (rc == 0) {
7984 mask = old_mask;
7985 /* bash messages:
7986 * bash: umask: 'q': invalid symbolic mode operator
7987 * bash: umask: 999: octal number out of range
7988 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02007989 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007990 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007991 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007992 rc = 1;
7993 /* Mimic bash */
7994 printf("%04o\n", (unsigned) mask);
7995 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007996 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007997 umask(mask);
7998
7999 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008000}
8001
Mike Frysingerd690f682009-03-30 06:50:54 +00008002/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008003static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008004{
Mike Frysingerd690f682009-03-30 06:50:54 +00008005 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008006 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008007
Denis Vlasenko28e67962009-04-26 23:22:40 +00008008 /* "!": do not abort on errors */
8009 /* "+": stop at 1st non-option */
8010 opts = getopt32(argv, "!+vf");
8011 if (opts == (unsigned)-1)
8012 return EXIT_FAILURE;
8013 if (opts == 3) {
8014 bb_error_msg("unset: -v and -f are exclusive");
8015 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008016 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008017 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008018
8019 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008020 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008021 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008022 if (unset_local_var(*argv)) {
8023 /* unset <nonexistent_var> doesn't fail.
8024 * Error is when one tries to unset RO var.
8025 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008026 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008027 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008028 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008029#if ENABLE_HUSH_FUNCTIONS
8030 else {
8031 unset_func(*argv);
8032 }
8033#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008034 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008035 }
8036 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008037}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008038
Mike Frysinger56bdea12009-03-28 20:01:58 +00008039/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008040static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008041{
8042 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008043 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008044
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008045 argv = skip_dash_dash(argv);
8046 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008047 /* Don't care about wait results */
8048 /* Note 1: must wait until there are no more children */
8049 /* Note 2: must be interruptible */
8050 /* Examples:
8051 * $ sleep 3 & sleep 6 & wait
8052 * [1] 30934 sleep 3
8053 * [2] 30935 sleep 6
8054 * [1] Done sleep 3
8055 * [2] Done sleep 6
8056 * $ sleep 3 & sleep 6 & wait
8057 * [1] 30936 sleep 3
8058 * [2] 30937 sleep 6
8059 * [1] Done sleep 3
8060 * ^C <-- after ~4 sec from keyboard
8061 * $
8062 */
8063 sigaddset(&G.blocked_set, SIGCHLD);
8064 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8065 while (1) {
8066 checkjobs(NULL);
8067 if (errno == ECHILD)
8068 break;
8069 /* Wait for SIGCHLD or any other signal of interest */
8070 /* sigtimedwait with infinite timeout: */
8071 sig = sigwaitinfo(&G.blocked_set, NULL);
8072 if (sig > 0) {
8073 sig = check_and_run_traps(sig);
8074 if (sig && sig != SIGCHLD) { /* see note 2 */
8075 ret = 128 + sig;
8076 break;
8077 }
8078 }
8079 }
8080 sigdelset(&G.blocked_set, SIGCHLD);
8081 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8082 return ret;
8083 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008084
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008085 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008086 while (*argv) {
8087 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008088 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008089 /* mimic bash message */
8090 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008091 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008092 }
8093 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008094 if (WIFSIGNALED(status))
8095 ret = 128 + WTERMSIG(status);
8096 else if (WIFEXITED(status))
8097 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008098 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008099 ret = EXIT_FAILURE;
8100 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008101 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008102 ret = 127;
8103 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008104 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008105 }
8106
8107 return ret;
8108}
8109
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008110#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8111static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8112{
8113 if (argv[1]) {
8114 def = bb_strtou(argv[1], NULL, 10);
8115 if (errno || def < def_min || argv[2]) {
8116 bb_error_msg("%s: bad arguments", argv[0]);
8117 def = UINT_MAX;
8118 }
8119 }
8120 return def;
8121}
8122#endif
8123
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008124#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008125static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008126{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008127 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008128 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008129 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008130 return EXIT_SUCCESS; /* bash compat */
8131 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008132 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008133
8134 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8135 if (depth == UINT_MAX)
8136 G.flag_break_continue = BC_BREAK;
8137 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008138 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008139
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008140 return EXIT_SUCCESS;
8141}
8142
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008143static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008144{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008145 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8146 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008147}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008148#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008149
8150#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008151static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008152{
8153 int rc;
8154
8155 if (G.flag_return_in_progress != -1) {
8156 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8157 return EXIT_FAILURE; /* bash compat */
8158 }
8159
8160 G.flag_return_in_progress = 1;
8161
8162 /* bash:
8163 * out of range: wraps around at 256, does not error out
8164 * non-numeric param:
8165 * f() { false; return qwe; }; f; echo $?
8166 * bash: return: qwe: numeric argument required <== we do this
8167 * 255 <== we also do this
8168 */
8169 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8170 return rc;
8171}
8172#endif