blob: 945077d87a9e03bcee15a514bf59058ff3ceaf28 [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);
Denys Vlasenko4f2c59b2010-05-21 01:25:16 +02002650 //bb_error_msg("beg:'%s'=%u end:'%s'", exp_word, beg, end);
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002651 if (*end == ':') {
2652 len = bb_strtou(end + 1, &end, 0);
2653 //bb_error_msg("len:%u end:'%s'", len, end);
2654 }
Denys Vlasenko4f2c59b2010-05-21 01:25:16 +02002655 if (*end == '\0') {
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002656 //bb_error_msg("from val:'%s'", val);
2657 if (!val || beg >= strlen(val))
2658 val = "";
2659 else
2660 val = dyn_val = xstrndup(val + beg, len);
2661 //bb_error_msg("val:'%s'", val);
2662 } else
2663#endif
2664 {
2665 die_if_script("malformed ${%s...}", var);
2666 }
2667 } else { /* one of "-=+?" */
Denys Vlasenko53b51332010-05-20 21:46:45 +02002668 /* Standard-mandated substitution ops:
2669 * ${var?word} - indicate error if unset
2670 * If var is unset, word (or a message indicating it is unset
2671 * if word is null) is written to standard error
2672 * and the shell exits with a non-zero exit status.
2673 * Otherwise, the value of var is substituted.
2674 * ${var-word} - use default value
2675 * If var is unset, word is substituted.
2676 * ${var=word} - assign and use default value
2677 * If var is unset, word is assigned to var.
2678 * In all cases, final value of var is substituted.
2679 * ${var+word} - use alternative value
2680 * If var is unset, null is substituted.
2681 * Otherwise, word is substituted.
2682 *
2683 * Word is subjected to tilde expansion, parameter expansion,
2684 * command substitution, and arithmetic expansion.
2685 * If word is not needed, it is not expanded.
2686 *
2687 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2688 * but also treat null var as if it is unset.
2689 */
2690 int use_word = (!val || ((exp_save == ':') && !val[0]));
Mike Frysingera4f331d2009-04-07 06:03:22 +00002691 if (exp_op == '+')
Denys Vlasenko53b51332010-05-20 21:46:45 +02002692 use_word = !use_word;
Mike Frysingera4f331d2009-04-07 06:03:22 +00002693 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
Denys Vlasenko53b51332010-05-20 21:46:45 +02002694 (exp_save == ':') ? "true" : "false", use_word);
2695 if (use_word) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002696 if (exp_op == '?') {
2697//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002698 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002699 die_if_script("%s: %s",
2700 var,
2701 exp_word[0] ? exp_word : "parameter null or not set"
2702 );
2703 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002704 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002705 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002706
Mike Frysingera4f331d2009-04-07 06:03:22 +00002707 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002708 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002709 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002710 /* mimic bash message */
2711 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002712 val = NULL;
2713 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002714 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002715 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002716 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002717 }
2718 }
2719 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002720
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002721 *exp_saveptr = exp_save;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002722 } /* if (exp_op) */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002723
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002724 arg[0] = first_ch;
2725#if ENABLE_HUSH_TICK
2726 store_val:
2727#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002728 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002729 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002730 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002731 /* unquoted var's contents should be globbed, so don't escape */
2732 smallint sv = output->o_escape;
2733 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002734 n = expand_on_ifs(output, n, val);
2735 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002736 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002737 }
2738 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002739 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002740 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002741 } /* default: */
2742 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002743
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002744 if (val) {
2745 o_addQstr(output, val, strlen(val));
2746 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002747 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002748 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002749 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002750 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002751
2752#if ENABLE_HUSH_TICK
2753 o_free(&subst_result);
2754#endif
2755 arg = ++p;
2756 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2757
2758 if (arg[0]) {
2759 debug_print_list("expand_vars_to_list[a]", output, n);
2760 /* this part is literal, and it was already pre-quoted
2761 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002762 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002763 debug_print_list("expand_vars_to_list[b]", output, n);
2764 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2765 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2766 ) {
2767 n--;
2768 /* allow to reuse list[n] later without re-growth */
2769 output->has_empty_slot = 1;
2770 } else {
2771 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002772 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002773 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002774}
2775
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002776static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002777{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002778 int n;
2779 char **list;
2780 char **v;
2781 o_string output = NULL_O_STRING;
2782
2783 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002784 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002785 /* (unquoted $var will temporarily switch it off) */
2786 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002787 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002788
2789 n = 0;
2790 v = argv;
2791 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002792 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002793 v++;
2794 }
2795 debug_print_list("expand_variables", &output, n);
2796
2797 /* output.data (malloced in one block) gets returned in "list" */
2798 list = o_finalize_list(&output, n);
2799 debug_print_strings("expand_variables[1]", list);
2800 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002801}
2802
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002803static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002804{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002805 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002806}
2807
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002808#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002809static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2810{
2811 return expand_variables(argv, 0x80);
2812}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002813#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002814
2815#ifdef CMD_SINGLEWORD_NOGLOB_COND
2816static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2817{
2818 int n;
2819 char **list;
2820 char **v;
2821 o_string output = NULL_O_STRING;
2822
2823 n = 0;
2824 v = argv;
2825 while (*v) {
2826 int is_var = is_well_formed_var_name(*v, '=');
2827 /* is_var * 0x80: singleword expansion for vars */
2828 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2829
2830 /* Subtle! expand_vars_to_list did not glob last word yet.
2831 * It does this only when fed with further data.
2832 * Therefore we set globbing flags AFTER it, not before:
2833 */
2834
2835 /* if it is not recognizably abc=...; then: */
2836 output.o_escape = !is_var; /* protect against globbing for "$var" */
2837 /* (unquoted $var will temporarily switch it off) */
2838 output.o_glob = !is_var; /* and indeed do globbing */
2839 v++;
2840 }
2841 debug_print_list("expand_cond", &output, n);
2842
2843 /* output.data (malloced in one block) gets returned in "list" */
2844 list = o_finalize_list(&output, n);
2845 debug_print_strings("expand_cond[1]", list);
2846 return list;
2847}
2848#endif
2849
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002850/* Used for expansion of right hand of assignments */
2851/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2852 * "v=/bin/c*" */
2853static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002854{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002855 char *argv[2], **list;
2856
2857 argv[0] = (char*)str;
2858 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002859 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002860 if (HUSH_DEBUG)
2861 if (!list[0] || list[1])
2862 bb_error_msg_and_die("BUG in varexp2");
2863 /* actually, just move string 2*sizeof(char*) bytes back */
2864 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002865 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002866 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2867 return (char*)list;
2868}
2869
2870/* Used for "eval" builtin */
2871static char* expand_strvec_to_string(char **argv)
2872{
2873 char **list;
2874
2875 list = expand_variables(argv, 0x80);
2876 /* Convert all NULs to spaces */
2877 if (list[0]) {
2878 int n = 1;
2879 while (list[n]) {
2880 if (HUSH_DEBUG)
2881 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2882 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002883 /* bash uses ' ' regardless of $IFS contents */
2884 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002885 n++;
2886 }
2887 }
2888 overlapping_strcpy((char*)list, list[0]);
2889 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2890 return (char*)list;
2891}
2892
2893static char **expand_assignments(char **argv, int count)
2894{
2895 int i;
2896 char **p = NULL;
2897 /* Expand assignments into one string each */
2898 for (i = 0; i < count; i++) {
2899 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2900 }
2901 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002902}
2903
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002904
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002905#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002906/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002907void re_execute_shell(char ***to_free, const char *s,
2908 char *g_argv0, char **g_argv,
2909 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002910
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002911static void reset_traps_to_defaults(void)
2912{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002913 /* This function is always called in a child shell
2914 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002915 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002916 unsigned sig;
2917 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002918
Denys Vlasenko67f71862009-09-25 14:21:06 +02002919 /* Child shells are not interactive.
2920 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2921 * Testcase: (while :; do :; done) + ^Z should background.
2922 * Same goes for SIGTERM, SIGHUP, SIGINT.
2923 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002924 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02002925 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002926
Denys Vlasenko67f71862009-09-25 14:21:06 +02002927 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2928 * Stupid. It can be done with *single* &= op, but we can't use
2929 * the fact that G.blocked_set is implemented as a bitmask
2930 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002931 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2932 sig = 1;
2933 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002934 if (mask & 1) {
2935 /* Careful. Only if no trap or trap is not "" */
2936 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2937 sigdelset(&G.blocked_set, sig);
2938 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002939 mask >>= 1;
2940 if (!mask)
2941 break;
2942 sig++;
2943 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02002944 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002945 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002946
2947 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002948 mask = G.non_DFL_mask;
2949 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002950 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002951 continue;
2952 free(G.traps[sig]);
2953 G.traps[sig] = NULL;
2954 /* There is no signal for 0 (EXIT) */
2955 if (sig == 0)
2956 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002957 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002958 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02002959 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002960 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002961 continue;
2962 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002963 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002964 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002965}
2966
2967#else /* !BB_MMU */
2968
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002969static void re_execute_shell(char ***to_free, const char *s,
2970 char *g_argv0, char **g_argv,
2971 char **builtin_argv) NORETURN;
2972static void re_execute_shell(char ***to_free, const char *s,
2973 char *g_argv0, char **g_argv,
2974 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002975{
Denys Vlasenko6c93b242010-01-12 19:28:10 +01002976#define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
2977 /* delims + 2 * (number of bytes in printed hex numbers) */
2978 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002979 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002980 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002981# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002982 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002983# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002984 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002985 unsigned cnt;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01002986 unsigned long long empty_trap_mask;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002987
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002988 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002989 argv = heredoc_argv;
2990 argv[0] = (char *) G.argv0_for_re_execing;
2991 argv[1] = (char *) "-<";
2992 argv[2] = (char *) s;
2993 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002994 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002995 goto do_exec;
2996 }
2997
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002998 cnt = 0;
2999 pp = builtin_argv;
3000 if (pp) while (*pp++)
3001 cnt++;
3002
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003003 empty_trap_mask = 0;
3004 if (G.traps) {
3005 int sig;
3006 for (sig = 1; sig < NSIG; sig++) {
3007 if (G.traps[sig] && !G.traps[sig][0])
3008 empty_trap_mask |= 1LL << sig;
3009 }
3010 }
3011
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003012 sprintf(param_buf, NOMMU_HACK_FMT
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003013 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02003014 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003015 , (unsigned) G.last_bg_pid
3016 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003017 , cnt
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003018 , empty_trap_mask
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003019 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003020 );
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003021#undef NOMMU_HACK_FMT
3022 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003023 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003024 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003025 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003026 for (cur = G.top_var; cur; cur = cur->next) {
3027 if (!cur->flg_export || cur->flg_read_only)
3028 cnt += 2;
3029 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003030# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003031 for (funcp = G.top_func; funcp; funcp = funcp->next)
3032 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003033# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003034 pp = g_argv;
3035 while (*pp++)
3036 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003037 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003038 *pp++ = (char *) G.argv0_for_re_execing;
3039 *pp++ = param_buf;
3040 for (cur = G.top_var; cur; cur = cur->next) {
3041 if (cur->varstr == hush_version_str)
3042 continue;
3043 if (cur->flg_read_only) {
3044 *pp++ = (char *) "-R";
3045 *pp++ = cur->varstr;
3046 } else if (!cur->flg_export) {
3047 *pp++ = (char *) "-V";
3048 *pp++ = cur->varstr;
3049 }
3050 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003051# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003052 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3053 *pp++ = (char *) "-F";
3054 *pp++ = funcp->name;
3055 *pp++ = funcp->body_as_string;
3056 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003057# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003058 /* We can pass activated traps here. Say, -Tnn:trap_string
3059 *
3060 * However, POSIX says that subshells reset signals with traps
3061 * to SIG_DFL.
3062 * I tested bash-3.2 and it not only does that with true subshells
3063 * of the form ( list ), but with any forked children shells.
3064 * I set trap "echo W" WINCH; and then tried:
3065 *
3066 * { echo 1; sleep 20; echo 2; } &
3067 * while true; do echo 1; sleep 20; echo 2; break; done &
3068 * true | { echo 1; sleep 20; echo 2; } | cat
3069 *
3070 * In all these cases sending SIGWINCH to the child shell
3071 * did not run the trap. If I add trap "echo V" WINCH;
3072 * _inside_ group (just before echo 1), it works.
3073 *
3074 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003075 * Even if we would use signal handlers instead of signal masking
3076 * in order to implement trap handling,
3077 * exec syscall below resets signals to SIG_DFL for us.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003078 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003079 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003080 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003081 if (builtin_argv) {
3082 while (*++builtin_argv)
3083 *pp++ = *builtin_argv;
3084 *pp++ = (char *) "";
3085 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003086 *pp++ = g_argv0;
3087 while (*g_argv)
3088 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003089 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003090 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003091
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003092 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003093 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3094 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003095 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003096 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003097 if (argv[0][0] == '/')
3098 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003099 xfunc_error_retval = 127;
3100 bb_error_msg_and_die("can't re-execute the shell");
3101}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003102#endif /* !BB_MMU */
3103
3104
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003105static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003106{
3107 struct fd_pair pair;
3108 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003109 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003110 /* the _body_ of heredoc (misleading field name) */
3111 const char *heredoc = redir->rd_filename;
3112 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003113#if !BB_MMU
3114 char **to_free;
3115#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003116
3117 expanded = NULL;
3118 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3119 expanded = expand_pseudo_dquoted(heredoc);
3120 if (expanded)
3121 heredoc = expanded;
3122 }
3123 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003124
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003125 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003126 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003127 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003128
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003129 /* Try writing without forking. Newer kernels have
3130 * dynamically growing pipes. Must use non-blocking write! */
3131 ndelay_on(pair.wr);
3132 while (1) {
3133 written = write(pair.wr, heredoc, len);
3134 if (written <= 0)
3135 break;
3136 len -= written;
3137 if (len == 0) {
3138 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00003139 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003140 return;
3141 }
3142 heredoc += written;
3143 }
3144 ndelay_off(pair.wr);
3145
3146 /* Okay, pipe buffer was not big enough */
3147 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003148 * for the unsuspecting parent process. Child creates a grandchild
3149 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003150 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003151#if !BB_MMU
3152 to_free = NULL;
3153#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003154 pid = vfork();
3155 if (pid < 0)
3156 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003157 if (pid == 0) {
3158 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003159 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003160 pid = BB_MMU ? fork() : vfork();
3161 if (pid < 0)
3162 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3163 if (pid != 0)
3164 _exit(0);
3165 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003166 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003167#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003168 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003169 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003170#else
3171 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003172 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003173 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003174#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003175 }
3176 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003177#if ENABLE_HUSH_FAST
3178 G.count_SIGCHLD++;
3179//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3180#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003181 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003182#if !BB_MMU
3183 free(to_free);
3184#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003185 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003186 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003187 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003188}
3189
Eric Andersen25f27032001-04-26 23:22:31 +00003190/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3191 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003192static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003193{
3194 int openfd, mode;
3195 struct redir_struct *redir;
3196
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003197 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003198 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003199 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003200 if (squirrel && redir->rd_fd < 3
3201 && squirrel[redir->rd_fd] < 0
3202 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003203 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003204 }
3205 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3206 * of the heredoc */
3207 debug_printf_parse("set heredoc '%s'\n",
3208 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003209 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003210 continue;
3211 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003212
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003213 if (redir->rd_dup == REDIRFD_TO_FILE) {
3214 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003215 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003216 if (redir->rd_filename == NULL) {
3217 /* Something went wrong in the parse.
3218 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003219 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003220 continue;
3221 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003222 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003223 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003224 openfd = open_or_warn(p, mode);
3225 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003226 if (openfd < 0) {
3227 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003228 * bash and ash both lose it as well (though zsh doesn't!) */
3229//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003230 return 1;
3231 }
3232 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003233 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003234 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003235 }
3236
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003237 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003238 if (squirrel && redir->rd_fd < 3
3239 && squirrel[redir->rd_fd] < 0
3240 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003241 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003242 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003243 if (openfd == REDIRFD_CLOSE) {
3244 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003245 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003246 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003247 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003248 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003249 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003250 }
Eric Andersen25f27032001-04-26 23:22:31 +00003251 }
3252 }
3253 return 0;
3254}
3255
3256static void restore_redirects(int squirrel[])
3257{
3258 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003259 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003260 fd = squirrel[i];
3261 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003262 /* We simply die on error */
3263 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003264 }
3265 }
3266}
3267
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003268
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003269static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003270
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003271/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003272static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003273{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003274 char **p;
3275 struct command *command;
3276 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003277 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003278
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003279 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003280 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003281 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003282 for (i = 0; i < pi->num_cmds; i++) {
3283 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003284 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003285 if (command->argv) {
3286 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003287 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003288 }
3289 free_strings(command->argv);
3290 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003291 }
3292 /* not "else if": on syntax error, we may have both! */
3293 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003294 debug_printf_clean(" begin group (cmd_type:%d)\n",
3295 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003296 free_pipe_list(command->group);
3297 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003298 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003299 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003300 /* else is crucial here.
3301 * If group != NULL, child_func is meaningless */
3302#if ENABLE_HUSH_FUNCTIONS
3303 else if (command->child_func) {
3304 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3305 command->child_func->parent_cmd = NULL;
3306 }
3307#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003308#if !BB_MMU
3309 free(command->group_as_string);
3310 command->group_as_string = NULL;
3311#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003312 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003313 debug_printf_clean(" redirect %d%s",
3314 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003315 /* guard against the case >$FOO, where foo is unset or blank */
3316 if (r->rd_filename) {
3317 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3318 free(r->rd_filename);
3319 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003320 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003321 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003322 rnext = r->next;
3323 free(r);
3324 }
3325 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003326 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003327 free(pi->cmds); /* children are an array, they get freed all at once */
3328 pi->cmds = NULL;
3329#if ENABLE_HUSH_JOB
3330 free(pi->cmdtext);
3331 pi->cmdtext = NULL;
3332#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003333}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003334
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003335static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003336{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003337 struct pipe *pi, *next;
3338
3339 for (pi = head; pi; pi = next) {
3340#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003341 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003342#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003343 free_pipe(pi);
3344 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003345 next = pi->next;
3346 /*pi->next = NULL;*/
3347 free(pi);
3348 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003349}
3350
3351
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003352static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003353#if BB_MMU
3354#define parse_stream(pstring, input, end_trigger) \
3355 parse_stream(input, end_trigger)
3356#endif
3357static struct pipe *parse_stream(char **pstring,
3358 struct in_str *input,
3359 int end_trigger);
3360static void parse_and_run_string(const char *s);
3361
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003362
Mike Frysinger93cadc22009-05-27 17:06:25 -04003363static char *find_in_path(const char *arg)
3364{
3365 char *ret = NULL;
3366 const char *PATH = get_local_var_value("PATH");
3367
3368 if (!PATH)
3369 return NULL;
3370
3371 while (1) {
3372 const char *end = strchrnul(PATH, ':');
3373 int sz = end - PATH; /* must be int! */
3374
3375 free(ret);
3376 if (sz != 0) {
3377 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3378 } else {
3379 /* We have xxx::yyyy in $PATH,
3380 * it means "use current dir" */
3381 ret = xstrdup(arg);
3382 }
3383 if (access(ret, F_OK) == 0)
3384 break;
3385
3386 if (*end == '\0') {
3387 free(ret);
3388 return NULL;
3389 }
3390 PATH = end + 1;
3391 }
3392
3393 return ret;
3394}
3395
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003396static const struct built_in_command* find_builtin_helper(const char *name,
3397 const struct built_in_command *x,
3398 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003399{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003400 while (x != end) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01003401 if (strcmp(name, x->b_cmd) != 0) {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003402 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003403 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003404 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003405 debug_printf_exec("found builtin '%s'\n", name);
3406 return x;
3407 }
3408 return NULL;
3409}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003410static const struct built_in_command* find_builtin1(const char *name)
3411{
3412 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3413}
3414static const struct built_in_command* find_builtin(const char *name)
3415{
3416 const struct built_in_command *x = find_builtin1(name);
3417 if (x)
3418 return x;
3419 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3420}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003421
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003422#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003423static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003424{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003425 struct function **funcpp = &G.top_func;
3426 while (*funcpp) {
3427 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003428 break;
3429 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003430 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003431 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003432 return funcpp;
3433}
3434
3435static const struct function *find_function(const char *name)
3436{
3437 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003438 if (funcp)
3439 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003440 return funcp;
3441}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003442
Denis Vlasenkobc569742009-04-12 20:35:19 +00003443/* Note: takes ownership on name ptr */
3444static struct function *new_function(char *name)
3445{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003446 struct function **funcpp = find_function_slot(name);
3447 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003448
Denys Vlasenko873273d2009-09-12 14:47:41 +02003449 if (funcp != NULL) {
3450 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003451 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3452 if (!cmd) {
3453 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3454 free(funcp->name);
3455 /* Note: if !funcp->body, do not free body_as_string!
3456 * This is a special case of "-F name body" function:
3457 * body_as_string was not malloced! */
3458 if (funcp->body) {
3459 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003460# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003461 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003462# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003463 }
3464 } else {
3465 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3466 cmd->argv[0] = funcp->name;
3467 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003468# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003469 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003470# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003471 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003472 } else {
3473 debug_printf_exec("remembering new function '%s'\n", name);
3474 funcp = *funcpp = xzalloc(sizeof(*funcp));
3475 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003476 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003477
Denis Vlasenkobc569742009-04-12 20:35:19 +00003478 funcp->name = name;
3479 return funcp;
3480}
3481
Denis Vlasenko40e84372009-04-18 11:23:38 +00003482static void unset_func(const char *name)
3483{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003484 struct function **funcpp = find_function_slot(name);
3485 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003486
Denys Vlasenko873273d2009-09-12 14:47:41 +02003487 if (funcp != NULL) {
3488 debug_printf_exec("freeing function '%s'\n", funcp->name);
3489 *funcpp = funcp->next;
3490 /* funcp is unlinked now, deleting it.
3491 * Note: if !funcp->body, the function was created by
3492 * "-F name body", do not free ->body_as_string
3493 * and ->name as they were not malloced. */
3494 if (funcp->body) {
3495 free_pipe_list(funcp->body);
3496 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003497# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003498 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003499# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003500 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003501 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003502 }
3503}
3504
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003505# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003506#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003507 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003508# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003509static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003510 const struct function *funcp,
3511 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003512static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003513 const struct function *funcp,
3514 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003515{
3516# if BB_MMU
3517 int n = 1;
3518
3519 argv[0] = G.global_argv[0];
3520 G.global_argv = argv;
3521 while (*++argv)
3522 n++;
3523 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003524 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003525 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003526 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003527 _exit(n);
3528# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003529 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003530 funcp->body_as_string,
3531 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003532 argv + 1,
3533 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003534# endif
3535}
3536
3537static int run_function(const struct function *funcp, char **argv)
3538{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003539 int rc;
3540 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003541 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003542
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003543 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003544
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003545 /* "we are in function, ok to use return" */
3546 sv_flg = G.flag_return_in_progress;
3547 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003548# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003549 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003550# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003551
Denis Vlasenkobc569742009-04-12 20:35:19 +00003552 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003553# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003554 if (!funcp->body) {
3555 /* Function defined by -F */
3556 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003557 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003558 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003559# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003560 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003561 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003562 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003563
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003564# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003565 {
3566 struct variable *var;
3567 struct variable **var_pp;
3568
3569 var_pp = &G.top_var;
3570 while ((var = *var_pp) != NULL) {
3571 if (var->func_nest_level < G.func_nest_level) {
3572 var_pp = &var->next;
3573 continue;
3574 }
3575 /* Unexport */
3576 if (var->flg_export)
3577 bb_unsetenv(var->varstr);
3578 /* Remove from global list */
3579 *var_pp = var->next;
3580 /* Free */
3581 if (!var->max_len)
3582 free(var->varstr);
3583 free(var);
3584 }
3585 G.func_nest_level--;
3586 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003587# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003588 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003589
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003590 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003591
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003592 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003593}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003594#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003595
3596
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003597#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003598#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003599 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003600#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003601#define exec_builtin(to_free, x, argv) \
3602 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003603#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003604static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003605 const struct built_in_command *x,
3606 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003607static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003608 const struct built_in_command *x,
3609 char **argv)
3610{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003611#if BB_MMU
Denys Vlasenko17323a62010-01-28 01:57:05 +01003612 int rcode = x->b_function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003613 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003614 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003615#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003616 /* On NOMMU, we must never block!
3617 * Example: { sleep 99 | read line; } & echo Ok
3618 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003619 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003620 argv[0],
3621 G.global_argv[0],
3622 G.global_argv + 1,
3623 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003624#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003625}
3626
3627
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003628static void execvp_or_die(char **argv) NORETURN;
3629static void execvp_or_die(char **argv)
3630{
3631 debug_printf_exec("execing '%s'\n", argv[0]);
3632 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3633 execvp(argv[0], argv);
3634 bb_perror_msg("can't execute '%s'", argv[0]);
3635 _exit(127); /* bash compat */
3636}
3637
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003638#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003639#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3640 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3641#define pseudo_exec(nommu_save, command, argv_expanded) \
3642 pseudo_exec(command, argv_expanded)
3643#endif
3644
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003645/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003646 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003647 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003648 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003649 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003650static void pseudo_exec_argv(nommu_save_t *nommu_save,
3651 char **argv, int assignment_cnt,
3652 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003653static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003654 char **argv, int assignment_cnt,
3655 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003656{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003657 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003658
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003659 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003660 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003661 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003662
Denis Vlasenko9504e442008-10-29 01:19:15 +00003663 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003664#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003665 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003666 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003667 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003668 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003669#else
3670 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003671 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003672#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003673 if (argv_expanded) {
3674 argv = argv_expanded;
3675 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003676 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003677#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003678 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003679#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003680 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003681
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003682#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3683 if (strchr(argv[0], '/') != NULL)
3684 goto skip;
3685#endif
3686
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003687 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003688 * Depending on context, this might be redundant. But it's
3689 * easier to waste a few CPU cycles than it is to figure out
3690 * if this is one of those cases.
3691 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003692 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003693 /* On NOMMU, it is more expensive to re-execute shell
3694 * just in order to run echo or test builtin.
3695 * It's better to skip it here and run corresponding
3696 * non-builtin later. */
3697 const struct built_in_command *x;
3698 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003699 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003700 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003701 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003702 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003703#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003704 /* Check if the command matches any functions */
3705 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003706 const struct function *funcp = find_function(argv[0]);
3707 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003708 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003709 }
3710 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003711#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003712
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003713#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003714 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003715 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003716 int a = find_applet_by_name(argv[0]);
3717 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003718# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003719 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003720 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003721 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003722 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003723# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003724 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003725 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003726 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3727 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003728 /* If they called chroot or otherwise made the binary no longer
3729 * executable, fall through */
3730 }
3731 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003732#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003733
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003734#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003735 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003736#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003737 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003738}
3739
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003740/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003741 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003742static void pseudo_exec(nommu_save_t *nommu_save,
3743 struct command *command,
3744 char **argv_expanded) NORETURN;
3745static void pseudo_exec(nommu_save_t *nommu_save,
3746 struct command *command,
3747 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003748{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003749 if (command->argv) {
3750 pseudo_exec_argv(nommu_save, command->argv,
3751 command->assignment_cnt, argv_expanded);
3752 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003753
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003754 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003755 /* Cases when we are here:
3756 * ( list )
3757 * { list } &
3758 * ... | ( list ) | ...
3759 * ... | { list } | ...
3760 */
3761#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003762 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003763 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003764 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003765 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003766 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003767 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003768 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003769#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003770 re_execute_shell(&nommu_save->argv_from_re_execing,
3771 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003772 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003773 G.global_argv + 1,
3774 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003775#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003776 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003777
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003778 /* Case when we are here: ... | >file */
3779 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003780 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003781}
3782
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003783#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003784static const char *get_cmdtext(struct pipe *pi)
3785{
3786 char **argv;
3787 char *p;
3788 int len;
3789
3790 /* This is subtle. ->cmdtext is created only on first backgrounding.
3791 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003792 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003793 if (pi->cmdtext)
3794 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003795 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003796 if (!argv || !argv[0]) {
3797 pi->cmdtext = xzalloc(1);
3798 return pi->cmdtext;
3799 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003800
3801 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003802 do {
3803 len += strlen(*argv) + 1;
3804 } while (*++argv);
3805 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003806 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003807 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003808 do {
3809 len = strlen(*argv);
3810 memcpy(p, *argv, len);
3811 p += len;
3812 *p++ = ' ';
3813 } while (*++argv);
3814 p[-1] = '\0';
3815 return pi->cmdtext;
3816}
3817
Eric Andersenbafd94f2001-05-02 16:11:59 +00003818static void insert_bg_job(struct pipe *pi)
3819{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003820 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003821 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003822
3823 /* Linear search for the ID of the job to use */
3824 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003825 for (job = G.job_list; job; job = job->next)
3826 if (job->jobid >= pi->jobid)
3827 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003828
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003829 /* Add job to the list of running jobs */
3830 jobp = &G.job_list;
3831 while ((job = *jobp) != NULL)
3832 jobp = &job->next;
3833 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003834
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003835 *job = *pi; /* physical copy */
3836 job->next = NULL;
3837 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3838 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003839 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003840 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003841 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003842 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003843 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003844
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003845 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003846 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3847 /* Last command's pid goes to $! */
3848 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3849 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003850}
3851
Eric Andersenbafd94f2001-05-02 16:11:59 +00003852static void remove_bg_job(struct pipe *pi)
3853{
3854 struct pipe *prev_pipe;
3855
Denis Vlasenko87a86552008-07-29 19:43:10 +00003856 if (pi == G.job_list) {
3857 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003858 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003859 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003860 while (prev_pipe->next != pi)
3861 prev_pipe = prev_pipe->next;
3862 prev_pipe->next = pi->next;
3863 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003864 if (G.job_list)
3865 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003866 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003867 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003868}
Eric Andersen028b65b2001-06-28 01:10:11 +00003869
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003870/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003871static void delete_finished_bg_job(struct pipe *pi)
3872{
3873 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003874 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003875 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003876 free(pi);
3877}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003878#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003879
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003880/* Check to see if any processes have exited -- if they
3881 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003882static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003883{
Eric Andersenc798b072001-06-22 06:23:03 +00003884 int attributes;
3885 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003886#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003887 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003888#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003889 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003890 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003891
Denis Vlasenkod5762932009-03-31 11:22:57 +00003892 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3893
Eric Andersenc798b072001-06-22 06:23:03 +00003894 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003895 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003896 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003897
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003898 errno = 0;
3899#if ENABLE_HUSH_FAST
3900 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3901//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3902//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003903 /* There was neither fork nor SIGCHLD since last waitpid */
3904 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003905 if (!G.we_have_children) {
3906 errno = ECHILD;
3907 return -1;
3908 }
3909 if (fg_pipe == NULL) { /* is WNOHANG set? */
3910 /* We have children, but they did not exit
3911 * or stop yet (we saw no SIGCHLD) */
3912 return 0;
3913 }
3914 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3915 }
3916#endif
3917
Denis Vlasenko1359da62007-04-21 23:27:30 +00003918/* Do we do this right?
3919 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003920 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003921 * [3]+ Stopped sleep 20 | false
3922 * bash-3.00# echo $?
3923 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003924 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003925 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003926 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003927 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003928 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003929 int dead;
3930
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003931#if ENABLE_HUSH_FAST
3932 i = G.count_SIGCHLD;
3933#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003934 childpid = waitpid(-1, &status, attributes);
3935 if (childpid <= 0) {
3936 if (childpid && errno != ECHILD)
3937 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003938#if ENABLE_HUSH_FAST
3939 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003940 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003941 G.handled_SIGCHLD = i;
3942//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3943 }
3944#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003945 break;
3946 }
3947 dead = WIFEXITED(status) || WIFSIGNALED(status);
3948
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003949#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003950 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003951 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003952 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3953 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003954 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003955 childpid, WTERMSIG(status), WEXITSTATUS(status));
3956 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003957 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003958 childpid, WEXITSTATUS(status));
3959#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003960 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003961 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003962 for (i = 0; i < fg_pipe->num_cmds; i++) {
3963 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3964 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003965 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003966 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003967 fg_pipe->cmds[i].pid = 0;
3968 fg_pipe->alive_cmds--;
3969 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003970 /* last process gives overall exitstatus */
3971 rcode = WEXITSTATUS(status);
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003972 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00003973 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003974 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003975 */
3976 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003977 int sig = WTERMSIG(status);
3978 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01003979 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
3980 * Maybe we need to use sig | 128? */
3981 rcode = sig + 128;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003982 }
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01003983 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003984 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003985 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003986 fg_pipe->cmds[i].is_stopped = 1;
3987 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003988 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003989 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3990 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3991 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003992 /* All processes in fg pipe have exited or stopped */
3993/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3994 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3995 * and "killall -STOP cat" */
3996 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003997#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003998 if (fg_pipe->alive_cmds)
3999 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004000#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004001 return rcode;
4002 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02004003 if (!fg_pipe->alive_cmds)
4004 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004005 }
4006 /* There are still running processes in the fg pipe */
4007 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00004008 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004009 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00004010 }
4011
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004012#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004013 /* We asked to wait for bg or orphaned children */
4014 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004015 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004016 for (i = 0; i < pi->num_cmds; i++) {
4017 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004018 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00004019 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00004020 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004021 /* Happens when shell is used as init process (init=/bin/sh) */
4022 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004023 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00004024
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004025 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00004026 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00004027 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004028 pi->cmds[i].pid = 0;
4029 pi->alive_cmds--;
4030 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004031 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00004032 printf(JOB_STATUS_FORMAT, pi->jobid,
4033 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004034 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004035 }
4036 } else {
4037 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004038 pi->cmds[i].is_stopped = 1;
4039 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004040 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004041#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004042 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004043
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004044 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00004045}
4046
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004047#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00004048static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4049{
4050 pid_t p;
4051 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04004052 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004053 /* Job finished, move the shell to the foreground */
4054 p = getpgrp(); /* our process group id */
4055 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4056 tcsetpgrp(G_interactive_fd, p);
4057 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00004058 return rcode;
4059}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004060#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00004061
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004062/* Start all the jobs, but don't wait for anything to finish.
4063 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00004064 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00004065 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00004066 * to finish to determine the exit status of the pipe. If the pipe
4067 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00004068 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00004069 * return value.
4070 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00004071 * Returns -1 only if started some children. IOW: we have to
4072 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00004073 *
4074 * The only case when we do not need to [v]fork is when the pipe
4075 * is single, non-backgrounded, non-subshell command. Examples:
4076 * cmd ; ... { list } ; ...
4077 * cmd && ... { list } && ...
4078 * cmd || ... { list } || ...
4079 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4080 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004081 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00004082 *
4083 * Cases when we must fork:
4084 * non-single: cmd | cmd
4085 * backgrounded: cmd & { list } &
4086 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00004087 */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02004088static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004089{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004090 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004091 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004092 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004093 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004094 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004095 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004096 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004097 /* it is not always needed, but we aim to smaller code */
4098 int squirrel[] = { -1, -1, -1 };
4099 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004100
Denis Vlasenko552433b2009-04-04 19:29:21 +00004101 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004102 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004103
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004104 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004105 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004106 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004107 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004108
Denis Vlasenko552433b2009-04-04 19:29:21 +00004109 if (pi->num_cmds != 1
4110 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004111 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00004112 ) {
4113 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004114 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004115
Denis Vlasenko552433b2009-04-04 19:29:21 +00004116 pi->alive_cmds = 1;
4117
4118 debug_printf_exec(": group:%p argv:'%s'\n",
4119 command->group, command->argv ? command->argv[0] : "NONE");
4120
4121 if (command->group) {
4122#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004123 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004124 /* "executing" func () { list } */
4125 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004126
Denis Vlasenkobc569742009-04-12 20:35:19 +00004127 funcp = new_function(command->argv[0]);
4128 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004129 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004130# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004131 funcp->body_as_string = command->group_as_string;
4132 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004133# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004134 command->group = NULL;
4135 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00004136 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4137 funcp->parent_cmd = command;
4138 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004139
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004140 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4141 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00004142 return EXIT_SUCCESS;
4143 }
4144#endif
4145 /* { list } */
4146 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004147 rcode = 1; /* exitcode if redir failed */
4148 if (setup_redirects(command, squirrel) == 0) {
4149 debug_printf_exec(": run_list\n");
4150 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004151 }
Eric Andersen04407e52001-06-07 16:42:05 +00004152 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004153 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004154 debug_leave();
4155 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004156 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004157 }
4158
Denis Vlasenko552433b2009-04-04 19:29:21 +00004159 argv = command->argv ? command->argv : (char **) &null_ptr;
4160 {
4161 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004162#if ENABLE_HUSH_FUNCTIONS
4163 const struct function *funcp;
4164#else
4165 enum { funcp = 0 };
4166#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004167 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004168 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004169
Denis Vlasenko552433b2009-04-04 19:29:21 +00004170 if (argv[command->assignment_cnt] == NULL) {
4171 /* Assignments, but no command */
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004172 /* Ensure redirects take effect (that is, create files).
4173 * Try "a=t >file": */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004174 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004175 restore_redirects(squirrel);
4176 /* Set shell variables */
4177 while (*argv) {
4178 p = expand_string_to_string(*argv);
4179 debug_printf_exec("set shell var:'%s'->'%s'\n",
4180 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004181 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004182 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004183 }
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004184 /* Redirect error sets $? to 1. Othervise,
4185 * if evaluating assignment value set $?, retain it.
4186 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4187 if (rcode == 0)
4188 rcode = G.last_exitcode;
Denis Vlasenko552433b2009-04-04 19:29:21 +00004189 /* Do we need to flag set_local_var() errors?
4190 * "assignment to readonly var" and "putenv error"
4191 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004192 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004193 debug_leave();
4194 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004195 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00004196 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004197
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004198 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004199 if (0) {}
4200#if ENABLE_HUSH_BASH_COMPAT
4201 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004202 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4203 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004204#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004205#ifdef CMD_SINGLEWORD_NOGLOB_COND
4206 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4207 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4208
4209 }
4210#endif
4211 else {
4212 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4213 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004214
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004215 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004216 if (!argv_expanded[0]) {
Denys Vlasenko385cc592010-01-12 06:47:39 +01004217 free(argv_expanded);
Mike Frysinger28736c32009-10-18 01:11:45 -04004218 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004219 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004220 }
4221
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004222 x = find_builtin(argv_expanded[0]);
4223#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004224 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004225 if (!x)
4226 funcp = find_function(argv_expanded[0]);
4227#endif
4228 if (x || funcp) {
4229 if (!funcp) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01004230 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004231 debug_printf("exec with redirects only\n");
4232 rcode = setup_redirects(command, NULL);
4233 goto clean_up_and_ret1;
4234 }
Eric Andersen25f27032001-04-26 23:22:31 +00004235 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004236 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004237 * This is perfect for work that comes after exec().
4238 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004239 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004240 rcode = setup_redirects(command, squirrel);
4241 if (rcode == 0) {
4242 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004243 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004244 if (!funcp) {
4245 debug_printf_exec(": builtin '%s' '%s'...\n",
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004246 x->b_cmd, argv_expanded[1]);
Denys Vlasenko17323a62010-01-28 01:57:05 +01004247 rcode = x->b_function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004248 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004249 }
4250#if ENABLE_HUSH_FUNCTIONS
4251 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004252# if ENABLE_HUSH_LOCAL
4253 struct variable **sv;
4254 sv = G.shadowed_vars_pp;
4255 G.shadowed_vars_pp = &old_vars;
4256# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004257 debug_printf_exec(": function '%s' '%s'...\n",
4258 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004259 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004260# if ENABLE_HUSH_LOCAL
4261 G.shadowed_vars_pp = sv;
4262# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004263 }
4264#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004265 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004266#if ENABLE_FEATURE_SH_STANDALONE
4267 clean_up_and_ret:
4268#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004269 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004270 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004271 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004272 clean_up_and_ret1:
4273 free(argv_expanded);
4274 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004275 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004276 debug_printf_exec("run_pipe return %d\n", rcode);
4277 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004278 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004279
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004280#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004281 i = find_applet_by_name(argv_expanded[0]);
4282 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004283 rcode = setup_redirects(command, squirrel);
4284 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004285 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004286 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004287 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004288 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004289 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004290 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004291 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004292 }
4293#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00004294 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004295 }
4296
Denis Vlasenko552433b2009-04-04 19:29:21 +00004297 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004298 /* NB: argv_expanded may already be created, and that
4299 * might include `cmd` runs! Do not rerun it! We *must*
4300 * use argv_expanded if it's non-NULL */
4301
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004302 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004303 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004304 nextin = 0;
4305
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004306 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004307 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004308#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004309 volatile nommu_save_t nommu_save;
4310 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004311 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004312 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004313 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004314#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004315 command = &(pi->cmds[i]);
4316 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004317 debug_printf_exec(": pipe member '%s' '%s'...\n",
4318 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004319 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004320 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004321 }
Eric Andersen25f27032001-04-26 23:22:31 +00004322
4323 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004324 pipefds.rd = 0;
4325 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004326 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004327 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004328
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004329 command->pid = BB_MMU ? fork() : vfork();
4330 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004331#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004332 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004333 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004334
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004335 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004336 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004337 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004338 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004339 pgrp = pi->pgrp;
4340 if (pgrp < 0) /* true for 1st process only */
4341 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004342 if (setpgid(0, pgrp) == 0
4343 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004344 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004345 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004346 /* We do it in *every* child, not just first,
4347 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004348 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004349 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004350 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004351#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004352 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4353 /* 1st cmd in backgrounded pipe
4354 * should have its stdin /dev/null'ed */
4355 close(0);
4356 if (open(bb_dev_null, O_RDONLY))
4357 xopen("/", O_RDONLY);
4358 } else {
4359 xmove_fd(nextin, 0);
4360 }
4361 xmove_fd(pipefds.wr, 1);
4362 if (pipefds.rd > 1)
4363 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004364 /* Like bash, explicit redirects override pipes,
4365 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004366 if (setup_redirects(command, NULL))
4367 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004368
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004369 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004370 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4371
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004372 /* Stores to nommu_save list of env vars putenv'ed
4373 * (NOMMU, on MMU we don't need that) */
4374 /* cast away volatility... */
4375 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004376 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004377 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004378
Denis Vlasenkof9375282009-04-05 19:13:39 +00004379 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004380#if ENABLE_HUSH_FAST
4381 G.count_SIGCHLD++;
4382//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4383#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004384 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004385#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004386 /* Clean up after vforked child */
4387 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004388 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004389 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004390 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004391#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004392 free(argv_expanded);
4393 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004394 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004395 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00004396 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004397 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004398 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004399#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004400 /* Second and next children need to know pid of first one */
4401 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004402 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004403#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004404 }
Eric Andersen25f27032001-04-26 23:22:31 +00004405
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004406 if (i)
4407 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004408 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004409 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004410 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004411 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004412 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004413
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004414 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004415 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004416 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4417 return 1;
4418 }
4419
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004420 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004421 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004422 return -1;
4423}
4424
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004425#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004426static void debug_print_tree(struct pipe *pi, int lvl)
4427{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004428 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004429 [PIPE_SEQ] = "SEQ",
4430 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004431 [PIPE_OR ] = "OR" ,
4432 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004433 };
4434 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004435 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004436# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004437 [RES_IF ] = "IF" ,
4438 [RES_THEN ] = "THEN" ,
4439 [RES_ELIF ] = "ELIF" ,
4440 [RES_ELSE ] = "ELSE" ,
4441 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004442# endif
4443# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004444 [RES_FOR ] = "FOR" ,
4445 [RES_WHILE] = "WHILE",
4446 [RES_UNTIL] = "UNTIL",
4447 [RES_DO ] = "DO" ,
4448 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004449# endif
4450# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004451 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004452# endif
4453# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004454 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004455 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004456 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004457 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004458 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004459# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004460 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004461 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004462 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004463 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004464 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004465 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004466 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004467# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004468 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004469# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004470 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004471
4472 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004473
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004474 pin = 0;
4475 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004476 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4477 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004478 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004479 while (prn < pi->num_cmds) {
4480 struct command *command = &pi->cmds[prn];
4481 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004482
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004483 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004484 lvl*2, "", prn,
4485 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004486 if (command->group) {
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004487 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004488 CMDTYPE[command->cmd_type],
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004489 argv
4490#if !BB_MMU
4491 , " group_as_string:", command->group_as_string
4492#else
4493 , "", ""
4494#endif
4495 );
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004496 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004497 prn++;
4498 continue;
4499 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004500 if (argv) while (*argv) {
4501 fprintf(stderr, " '%s'", *argv);
4502 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004503 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004504 fprintf(stderr, "\n");
4505 prn++;
4506 }
4507 pi = pi->next;
4508 pin++;
4509 }
4510}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004511#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004512
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004513/* NB: called by pseudo_exec, and therefore must not modify any
4514 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004515static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004516{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004517#if ENABLE_HUSH_CASE
4518 char *case_word = NULL;
4519#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004520#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004521 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004522 char **for_lcur = NULL;
4523 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004524#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004525 smallint last_followup;
4526 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004527#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004528 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004529#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004530 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004531#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004532#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004533 smallint rword; /* enum reserved_style */
4534 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004535#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004536
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004537 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004538 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004539
Denis Vlasenko06810332007-05-21 23:30:54 +00004540#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004541 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004542 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4543 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004544 continue;
4545 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004546 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004547 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004548 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004549 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004550 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004551 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004552 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004553 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004554 continue;
4555 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004556 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4557 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004558 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004559 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004560 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004561 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004562 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004563 }
4564 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004565#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004566
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004567 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004568 * in order to return, no direct "return" statements please.
4569 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004570
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004571#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004572 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004573#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004574
Denis Vlasenko0e151382009-04-06 18:40:31 +00004575#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004576 rword = RES_NONE;
4577 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004578#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004579 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004580 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004581
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004582 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004583 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004584 if (G.flag_SIGINT)
4585 break;
4586
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004587 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004588 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4589 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004590#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004591 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004592 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004593 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004594 /* start of a loop: remember where loop starts */
4595 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004596 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004597 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004598#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004599 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004600 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004601 if ((rcode == 0 && last_followup == PIPE_OR)
4602 || (rcode != 0 && last_followup == PIPE_AND)
4603 ) {
4604 /* It is "<true> || CMD" or "<false> && CMD"
4605 * and we should not execute CMD */
4606 debug_printf_exec("skipped cmd because of || or &&\n");
4607 last_followup = pi->followup;
4608 continue;
4609 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004610 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004611 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004612 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004613#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004614 if (cond_code) {
4615 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004616 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004617 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004618 /* "if <false> THEN cmd": skip cmd */
4619 continue;
4620 }
4621 } else {
4622 if (rword == RES_ELSE || rword == RES_ELIF) {
4623 /* "if <true> then ... ELSE/ELIF cmd":
4624 * skip cmd and all following ones */
4625 break;
4626 }
4627 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004628#endif
4629#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004630 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004631 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004632 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004633
4634 static const char encoded_dollar_at[] ALIGN1 = {
4635 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4636 }; /* encoded representation of "$@" */
4637 static const char *const encoded_dollar_at_argv[] = {
4638 encoded_dollar_at, NULL
4639 }; /* argv list with one element: "$@" */
4640 char **vals;
4641
4642 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004643 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004644 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004645 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004646 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004647 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004648 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004649 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004650 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004651 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004652 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004653 debug_print_strings("for_list made from", vals);
4654 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004655 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004656 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004657 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004658 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004659 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004660 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004661 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004662 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004663 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004664 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004665 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004666 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004667 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 +02004668 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004669 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004670 if (rword == RES_IN) {
4671 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4672 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004673 if (rword == RES_DONE) {
4674 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004675 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004676#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004677#if ENABLE_HUSH_CASE
4678 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004679 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004680 continue;
4681 }
4682 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004683 char **argv;
4684
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004685 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4686 break;
4687 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004688 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004689 while (*argv) {
4690 char *pattern = expand_string_to_string(*argv);
4691 /* TODO: which FNM_xxx flags to use? */
4692 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4693 free(pattern);
4694 if (cond_code == 0) { /* match! we will execute this branch */
4695 free(case_word); /* make future "word)" stop */
4696 case_word = NULL;
4697 break;
4698 }
4699 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004700 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004701 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004702 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004703 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004704 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004705 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004706 }
4707#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004708 /* Just pressing <enter> in shell should check for jobs.
4709 * OTOH, in non-interactive shell this is useless
4710 * and only leads to extra job checks */
4711 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004712 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004713 goto check_jobs_and_continue;
4714 continue;
4715 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004716
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004717 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004718 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004719 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004720 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004721 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004722 {
4723 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004724#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004725 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004726#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004727 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4728 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004729 /* We ran a builtin, function, or group.
4730 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004731 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004732 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004733 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004734 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004735#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004736 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004737 if (G.flag_break_continue) {
4738 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004739 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004740 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004741 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004742 G.depth_break_continue--;
4743 if (G.depth_break_continue == 0)
4744 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004745 /* else: e.g. "continue 2" should *break* once, *then* continue */
4746 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004747 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004748 goto check_jobs_and_break;
4749 /* "continue": simulate end of loop */
4750 rword = RES_DONE;
4751 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004752 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004753#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004754#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004755 if (G.flag_return_in_progress == 1) {
4756 /* same as "goto check_jobs_and_break" */
4757 checkjobs(NULL);
4758 break;
4759 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004760#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004761 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004762 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004763 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004764 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4765 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004766 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004767#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004768 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004769 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004770#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004771 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004772 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004773 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004774#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004775 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004776 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004777 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004778 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004779 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004780 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004781#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004782 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004783 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004784 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004785 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004786 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004787 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004788 }
4789 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004790
4791 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004792#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004793 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004794 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004795#endif
4796#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004797 /* Beware of "while false; true; do ..."! */
4798 if (pi->next && pi->next->res_word == RES_DO) {
4799 if (rword == RES_WHILE) {
4800 if (rcode) {
4801 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004802 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004803 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4804 goto check_jobs_and_break;
4805 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004806 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004807 if (rword == RES_UNTIL) {
4808 if (!rcode) {
4809 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004810 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004811 checkjobs(NULL);
4812 break;
4813 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004814 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004815 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004816#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004817
4818 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004819 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004820 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004821
4822#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004823 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004824#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004825#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004826 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004827 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004828 free(for_list);
4829#endif
4830#if ENABLE_HUSH_CASE
4831 free(case_word);
4832#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004833 debug_leave();
4834 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004835 return rcode;
4836}
4837
Eric Andersen25f27032001-04-26 23:22:31 +00004838/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004839static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004840{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004841 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004842 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004843 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004844 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004845 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004846 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004847 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004848 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004849 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004850 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004851 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004852 return rcode;
4853}
4854
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004855
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004856static struct pipe *new_pipe(void)
4857{
Eric Andersen25f27032001-04-26 23:22:31 +00004858 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004859 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004860 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004861 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004862 return pi;
4863}
4864
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004865/* Command (member of a pipe) is complete, or we start a new pipe
4866 * if ctx->command is NULL.
4867 * No errors possible here.
4868 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004869static int done_command(struct parse_context *ctx)
4870{
4871 /* The command is really already in the pipe structure, so
4872 * advance the pipe counter and make a new, null command. */
4873 struct pipe *pi = ctx->pipe;
4874 struct command *command = ctx->command;
4875
4876 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004877 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004878 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004879 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004880 }
4881 pi->num_cmds++;
4882 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004883 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004884 } else {
4885 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4886 }
4887
4888 /* Only real trickiness here is that the uncommitted
4889 * command structure is not counted in pi->num_cmds. */
4890 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004891 ctx->command = command = &pi->cmds[pi->num_cmds];
4892 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004893 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004894 return pi->num_cmds; /* used only for 0/nonzero check */
4895}
4896
4897static void done_pipe(struct parse_context *ctx, pipe_style type)
4898{
4899 int not_null;
4900
4901 debug_printf_parse("done_pipe entered, followup %d\n", type);
4902 /* Close previous command */
4903 not_null = done_command(ctx);
4904 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004905#if HAS_KEYWORDS
4906 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4907 ctx->ctx_inverted = 0;
4908 ctx->pipe->res_word = ctx->ctx_res_w;
4909#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004910
4911 /* Without this check, even just <enter> on command line generates
4912 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004913 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004914 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004915#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004916 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004917#endif
4918#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004919 || ctx->ctx_res_w == RES_DONE
4920 || ctx->ctx_res_w == RES_FOR
4921 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004922#endif
4923#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004924 || ctx->ctx_res_w == RES_ESAC
4925#endif
4926 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004927 struct pipe *new_p;
4928 debug_printf_parse("done_pipe: adding new pipe: "
4929 "not_null:%d ctx->ctx_res_w:%d\n",
4930 not_null, ctx->ctx_res_w);
4931 new_p = new_pipe();
4932 ctx->pipe->next = new_p;
4933 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004934 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004935 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004936 * This is used to control execution.
4937 * RES_FOR and RES_IN are NOT sticky (needed to support
4938 * cases where variable or value happens to match a keyword):
4939 */
4940#if ENABLE_HUSH_LOOPS
4941 if (ctx->ctx_res_w == RES_FOR
4942 || ctx->ctx_res_w == RES_IN)
4943 ctx->ctx_res_w = RES_NONE;
4944#endif
4945#if ENABLE_HUSH_CASE
4946 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004947 ctx->ctx_res_w = RES_CASE_BODY;
4948 if (ctx->ctx_res_w == RES_CASE)
4949 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004950#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004951 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004952 /* Create the memory for command, roughly:
4953 * ctx->pipe->cmds = new struct command;
4954 * ctx->command = &ctx->pipe->cmds[0];
4955 */
4956 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004957 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004958 }
4959 debug_printf_parse("done_pipe return\n");
4960}
4961
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004962static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004963{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004964 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004965 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004966 /* Create the memory for command, roughly:
4967 * ctx->pipe->cmds = new struct command;
4968 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004969 */
4970 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004971}
4972
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004973/* If a reserved word is found and processed, parse context is modified
4974 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004975 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004976#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004977struct reserved_combo {
4978 char literal[6];
4979 unsigned char res;
4980 unsigned char assignment_flag;
4981 int flag;
4982};
4983enum {
4984 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004985# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004986 FLAG_IF = (1 << RES_IF ),
4987 FLAG_THEN = (1 << RES_THEN ),
4988 FLAG_ELIF = (1 << RES_ELIF ),
4989 FLAG_ELSE = (1 << RES_ELSE ),
4990 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004991# endif
4992# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004993 FLAG_FOR = (1 << RES_FOR ),
4994 FLAG_WHILE = (1 << RES_WHILE),
4995 FLAG_UNTIL = (1 << RES_UNTIL),
4996 FLAG_DO = (1 << RES_DO ),
4997 FLAG_DONE = (1 << RES_DONE ),
4998 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004999# endif
5000# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005001 FLAG_MATCH = (1 << RES_MATCH),
5002 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005003# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005004 FLAG_START = (1 << RES_XXXX ),
5005};
5006
5007static const struct reserved_combo* match_reserved_word(o_string *word)
5008{
Eric Andersen25f27032001-04-26 23:22:31 +00005009 /* Mostly a list of accepted follow-up reserved words.
5010 * FLAG_END means we are done with the sequence, and are ready
5011 * to turn the compound list into a command.
5012 * FLAG_START means the word must start a new compound list.
5013 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005014 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005015# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005016 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5017 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5018 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5019 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5020 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5021 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005022# endif
5023# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005024 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5025 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5026 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5027 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5028 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5029 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005030# endif
5031# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005032 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5033 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005034# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005035 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005036 const struct reserved_combo *r;
5037
5038 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5039 if (strcmp(word->data, r->literal) == 0)
5040 return r;
5041 }
5042 return NULL;
5043}
Denis Vlasenkobb929512009-04-16 10:59:40 +00005044/* Return 0: not a keyword, 1: keyword
5045 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005046static int reserved_word(o_string *word, struct parse_context *ctx)
5047{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005048# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005049 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005050 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005051 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005052# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005053 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005054
Denis Vlasenkobb929512009-04-16 10:59:40 +00005055 if (word->o_quoted)
5056 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005057 r = match_reserved_word(word);
5058 if (!r)
5059 return 0;
5060
5061 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005062# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005063 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5064 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005065 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005066 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005067# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005068 if (r->flag == 0) { /* '!' */
5069 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005070 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00005071 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00005072 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005073 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005074 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005075 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005076 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005077 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005078
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005079 old = xmalloc(sizeof(*old));
5080 debug_printf_parse("push stack %p\n", old);
5081 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005082 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005083 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005084 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005085 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005086 ctx->ctx_res_w = RES_SNTX;
5087 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005088 } else {
5089 /* "{...} fi" is ok. "{...} if" is not
5090 * Example:
5091 * if { echo foo; } then { echo bar; } fi */
5092 if (ctx->command->group)
5093 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005094 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00005095
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005096 ctx->ctx_res_w = r->res;
5097 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005098 word->o_assignment = r->assignment_flag;
5099
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005100 if (ctx->old_flag & FLAG_END) {
5101 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005102
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005103 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005104 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005105 old = ctx->stack;
5106 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005107 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005108# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005109 o_addstr(&old->as_string, ctx->as_string.data);
5110 o_free_unsafe(&ctx->as_string);
5111 old->command->group_as_string = xstrdup(old->as_string.data);
5112 debug_printf_parse("pop, remembering as:'%s'\n",
5113 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005114# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005115 *ctx = *old; /* physical copy */
5116 free(old);
5117 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005118 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005119}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005120#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00005121
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005122/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005123 * Normal return is 0. Syntax errors return 1.
5124 * Note: on return, word is reset, but not o_free'd!
5125 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005126static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005127{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005128 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00005129
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005130 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005131 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005132 debug_printf_parse("done_word return 0: true null, ignored\n");
5133 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005134 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005135
Eric Andersen25f27032001-04-26 23:22:31 +00005136 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005137 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5138 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005139 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5140 * "2.7 Redirection
5141 * ...the word that follows the redirection operator
5142 * shall be subjected to tilde expansion, parameter expansion,
5143 * command substitution, arithmetic expansion, and quote
5144 * removal. Pathname expansion shall not be performed
5145 * on the word by a non-interactive shell; an interactive
5146 * shell may perform it, but shall do so only when
5147 * the expansion would result in one word."
5148 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005149 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005150 /* Cater for >\file case:
5151 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5152 * Same with heredocs:
5153 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5154 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005155 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5156 unbackslash(ctx->pending_redirect->rd_filename);
5157 /* Is it <<"HEREDOC"? */
5158 if (word->o_quoted) {
5159 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5160 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005161 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005162 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005163 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00005164 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005165 /* If this word wasn't an assignment, next ones definitely
5166 * can't be assignments. Even if they look like ones. */
5167 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5168 && word->o_assignment != WORD_IS_KEYWORD
5169 ) {
5170 word->o_assignment = NOT_ASSIGNMENT;
5171 } else {
5172 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5173 command->assignment_cnt++;
5174 word->o_assignment = MAYBE_ASSIGNMENT;
5175 }
5176
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005177#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005178# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00005179 if (ctx->ctx_dsemicolon
5180 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5181 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00005182 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005183 /* ctx->ctx_res_w = RES_MATCH; */
5184 ctx->ctx_dsemicolon = 0;
5185 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005186# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005187 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005188# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005189 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5190 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005191# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005192# if ENABLE_HUSH_CASE
5193 && ctx->ctx_res_w != RES_CASE
5194# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005195 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005196 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005197 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005198 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005199 debug_printf_parse("done_word return %d\n",
5200 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005201 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005202 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005203# ifdef CMD_SINGLEWORD_NOGLOB_COND
5204 if (strcmp(word->data, "export") == 0
5205# if ENABLE_HUSH_LOCAL
5206 || strcmp(word->data, "local") == 0
5207# endif
5208 ) {
5209 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5210 } else
5211# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005212# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005213 if (strcmp(word->data, "[[") == 0) {
5214 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5215 }
5216 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005217# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005218 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005219#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005220 if (command->group) {
5221 /* "{ echo foo; } echo bar" - bad */
5222 syntax_error_at(word->data);
5223 debug_printf_parse("done_word return 1: syntax error, "
5224 "groups and arglists don't mix\n");
5225 return 1;
5226 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005227 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005228 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5229 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005230 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005231 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005232 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005233 char *p = word->data;
5234 while (p[0] == SPECIAL_VAR_SYMBOL
5235 && (p[1] & 0x7f) == '@'
5236 && p[2] == SPECIAL_VAR_SYMBOL
5237 ) {
5238 p += 3;
5239 }
5240 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005241 /* saw no "$@", or not only "$@" but some
5242 * real text is there too */
5243 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005244 * e.g. "", $empty"" etc to not disappear */
5245 o_addchr(word, SPECIAL_VAR_SYMBOL);
5246 o_addchr(word, SPECIAL_VAR_SYMBOL);
5247 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005248 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005249 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005250 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005251 }
Eric Andersen25f27032001-04-26 23:22:31 +00005252
Denis Vlasenko06810332007-05-21 23:30:54 +00005253#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005254 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005255 if (word->o_quoted
5256 || !is_well_formed_var_name(command->argv[0], '\0')
5257 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005258 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005259 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005260 return 1;
5261 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005262 /* Force FOR to have just one word (variable name) */
5263 /* NB: basically, this makes hush see "for v in ..."
5264 * syntax as if it is "for v; in ...". FOR and IN become
5265 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005266 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005267 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005268#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005269#if ENABLE_HUSH_CASE
5270 /* Force CASE to have just one word */
5271 if (ctx->ctx_res_w == RES_CASE) {
5272 done_pipe(ctx, PIPE_SEQ);
5273 }
5274#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005275
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005276 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005277
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005278 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005279 return 0;
5280}
5281
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005282
5283/* Peek ahead in the input to find out if we have a "&n" construct,
5284 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005285 * Return:
5286 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5287 * REDIRFD_SYNTAX_ERR if syntax error,
5288 * REDIRFD_TO_FILE if no & was seen,
5289 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005290 */
5291#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005292#define parse_redir_right_fd(as_string, input) \
5293 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005294#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005295static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005296{
5297 int ch, d, ok;
5298
5299 ch = i_peek(input);
5300 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005301 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005302
5303 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005304 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005305 ch = i_peek(input);
5306 if (ch == '-') {
5307 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005308 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005309 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005310 }
5311 d = 0;
5312 ok = 0;
5313 while (ch != EOF && isdigit(ch)) {
5314 d = d*10 + (ch-'0');
5315 ok = 1;
5316 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005317 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005318 ch = i_peek(input);
5319 }
5320 if (ok) return d;
5321
5322//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5323
5324 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005325 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005326}
5327
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005328/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005329 */
5330static int parse_redirect(struct parse_context *ctx,
5331 int fd,
5332 redir_type style,
5333 struct in_str *input)
5334{
5335 struct command *command = ctx->command;
5336 struct redir_struct *redir;
5337 struct redir_struct **redirp;
5338 int dup_num;
5339
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005340 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005341 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005342 /* Check for a '>&1' type redirect */
5343 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5344 if (dup_num == REDIRFD_SYNTAX_ERR)
5345 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005346 } else {
5347 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005348 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005349 if (dup_num) { /* <<-... */
5350 ch = i_getch(input);
5351 nommu_addchr(&ctx->as_string, ch);
5352 ch = i_peek(input);
5353 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005354 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005355
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005356 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005357 int ch = i_peek(input);
5358 if (ch == '|') {
5359 /* >|FILE redirect ("clobbering" >).
5360 * Since we do not support "set -o noclobber" yet,
5361 * >| and > are the same for now. Just eat |.
5362 */
5363 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005364 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005365 }
5366 }
5367
5368 /* Create a new redir_struct and append it to the linked list */
5369 redirp = &command->redirects;
5370 while ((redir = *redirp) != NULL) {
5371 redirp = &(redir->next);
5372 }
5373 *redirp = redir = xzalloc(sizeof(*redir));
5374 /* redir->next = NULL; */
5375 /* redir->rd_filename = NULL; */
5376 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005377 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005378
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005379 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5380 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005381
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005382 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005383 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005384 /* Erik had a check here that the file descriptor in question
5385 * is legit; I postpone that to "run time"
5386 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005387 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5388 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005389 } else {
5390 /* Set ctx->pending_redirect, so we know what to do at the
5391 * end of the next parsed word. */
5392 ctx->pending_redirect = redir;
5393 }
5394 return 0;
5395}
5396
Eric Andersen25f27032001-04-26 23:22:31 +00005397/* If a redirect is immediately preceded by a number, that number is
5398 * supposed to tell which file descriptor to redirect. This routine
5399 * looks for such preceding numbers. In an ideal world this routine
5400 * needs to handle all the following classes of redirects...
5401 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5402 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5403 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5404 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005405 *
5406 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5407 * "2.7 Redirection
5408 * ... If n is quoted, the number shall not be recognized as part of
5409 * the redirection expression. For example:
5410 * echo \2>a
5411 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005412 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005413 *
5414 * A -1 return means no valid number was found,
5415 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005416 */
5417static int redirect_opt_num(o_string *o)
5418{
5419 int num;
5420
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005421 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005422 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005423 num = bb_strtou(o->data, NULL, 10);
5424 if (errno || num < 0)
5425 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005426 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005427 return num;
5428}
5429
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005430#if BB_MMU
5431#define fetch_till_str(as_string, input, word, skip_tabs) \
5432 fetch_till_str(input, word, skip_tabs)
5433#endif
5434static char *fetch_till_str(o_string *as_string,
5435 struct in_str *input,
5436 const char *word,
5437 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005438{
5439 o_string heredoc = NULL_O_STRING;
5440 int past_EOL = 0;
5441 int ch;
5442
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005443 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005444 while (1) {
5445 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005446 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005447 if (ch == '\n') {
5448 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5449 heredoc.data[past_EOL] = '\0';
5450 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5451 return heredoc.data;
5452 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005453 do {
5454 o_addchr(&heredoc, ch);
5455 past_EOL = heredoc.length;
5456 jump_in:
5457 do {
5458 ch = i_getch(input);
5459 nommu_addchr(as_string, ch);
5460 } while (skip_tabs && ch == '\t');
5461 } while (ch == '\n');
5462 }
5463 if (ch == EOF) {
5464 o_free_unsafe(&heredoc);
5465 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005466 }
5467 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005468 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005469 }
5470}
5471
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005472/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5473 * and load them all. There should be exactly heredoc_cnt of them.
5474 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005475static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5476{
5477 struct pipe *pi = ctx->list_head;
5478
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005479 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005480 int i;
5481 struct command *cmd = pi->cmds;
5482
5483 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5484 pi->num_cmds,
5485 cmd->argv ? cmd->argv[0] : "NONE");
5486 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005487 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005488
5489 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5490 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005491 while (redir) {
5492 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005493 char *p;
5494
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005495 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005496 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005497 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005498 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005499 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005500 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005501 return 1;
5502 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005503 free(redir->rd_filename);
5504 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005505 heredoc_cnt--;
5506 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005507 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005508 }
5509 cmd++;
5510 }
5511 pi = pi->next;
5512 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005513#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005514 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005515 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005516 bb_error_msg_and_die("heredoc BUG 2");
5517#endif
5518 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005519}
5520
5521
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005522#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005523static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005524{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005525 pid_t pid;
5526 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005527# if !BB_MMU
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01005528 char **to_free = NULL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005529# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005530
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005531 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00005532 pid = BB_MMU ? fork() : vfork();
5533 if (pid < 0)
5534 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005535
Denis Vlasenko05743d72008-02-10 12:10:08 +00005536 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005537 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005538 /* Process substitution is not considered to be usual
5539 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005540 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5541 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005542 bb_signals(0
5543 + (1 << SIGTSTP)
5544 + (1 << SIGTTIN)
5545 + (1 << SIGTTOU)
5546 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005547 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005548 close(channel[0]); /* NB: close _first_, then move fd! */
5549 xmove_fd(channel[1], 1);
5550 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005551 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005552 /* Awful hack for `trap` or $(trap).
5553 *
5554 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5555 * contains an example where "trap" is executed in a subshell:
5556 *
5557 * save_traps=$(trap)
5558 * ...
5559 * eval "$save_traps"
5560 *
5561 * Standard does not say that "trap" in subshell shall print
5562 * parent shell's traps. It only says that its output
5563 * must have suitable form, but then, in the above example
5564 * (which is not supposed to be normative), it implies that.
5565 *
5566 * bash (and probably other shell) does implement it
5567 * (traps are reset to defaults, but "trap" still shows them),
5568 * but as a result, "trap" logic is hopelessly messed up:
5569 *
5570 * # trap
5571 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5572 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5573 * # true | trap <--- trap is in subshell - no output (ditto)
5574 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5575 * trap -- 'echo Ho' SIGWINCH
5576 * # echo `(trap)` <--- in subshell in subshell - output
5577 * trap -- 'echo Ho' SIGWINCH
5578 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5579 * trap -- 'echo Ho' SIGWINCH
5580 *
5581 * The rules when to forget and when to not forget traps
5582 * get really complex and nonsensical.
5583 *
5584 * Our solution: ONLY bare $(trap) or `trap` is special.
5585 */
5586 s = skip_whitespace(s);
5587 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5588 {
5589 static const char *const argv[] = { NULL, NULL };
5590 builtin_trap((char**)argv);
5591 exit(0); /* not _exit() - we need to fflush */
5592 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005593# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005594 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005595 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005596 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005597# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005598 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005599 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5600 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005601 * echo OK
5602 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005603 re_execute_shell(&to_free,
5604 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005605 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005606 G.global_argv + 1,
5607 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005608# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005609 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005610
5611 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005612 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005613# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005614 G.count_SIGCHLD++;
5615//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 +02005616# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005617 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005618# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005619 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005620# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005621 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005622 close_on_exec_on(channel[0]);
5623 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005624}
5625
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005626/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005627static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005628{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005629 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005630 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005631 pid_t pid;
5632 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005633
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005634 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005635
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005636 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005637 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005638 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005639 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005640 if (ch == '\n') {
5641 eol_cnt++;
5642 continue;
5643 }
5644 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005645 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005646 eol_cnt--;
5647 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005648 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005649 }
5650
Denys Vlasenko647553a2009-11-15 19:58:19 +01005651 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005652 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005653 /* We need to extract exitcode. Test case
5654 * "true; echo `sleep 1; false` $?"
5655 * should print 1 */
5656 safe_waitpid(pid, &status, 0);
5657 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5658 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005659}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005660#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005661
Denys Vlasenkoc2704542009-11-20 19:14:19 +01005662#if !ENABLE_HUSH_FUNCTIONS
5663#define parse_group(dest, ctx, input, ch) \
5664 parse_group(ctx, input, ch)
5665#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005666static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005667 struct in_str *input, int ch)
5668{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005669 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005670 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005671 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005672 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005673 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005674 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005675
5676 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005677#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005678 if (ch == '(' && !dest->o_quoted) {
5679 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005680 if (done_word(dest, ctx))
5681 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005682 if (!command->argv)
5683 goto skip; /* (... */
5684 if (command->argv[1]) { /* word word ... (... */
5685 syntax_error_unexpected_ch('(');
5686 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005687 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005688 /* it is "word(..." or "word (..." */
5689 do
5690 ch = i_getch(input);
5691 while (ch == ' ' || ch == '\t');
5692 if (ch != ')') {
5693 syntax_error_unexpected_ch(ch);
5694 return 1;
5695 }
5696 nommu_addchr(&ctx->as_string, ch);
5697 do
5698 ch = i_getch(input);
5699 while (ch == ' ' || ch == '\t' || ch == '\n');
5700 if (ch != '{') {
5701 syntax_error_unexpected_ch(ch);
5702 return 1;
5703 }
5704 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005705 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005706 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005707 }
5708#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005709
5710#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005711 if (command->argv /* word [word]{... */
5712 || dest->length /* word{... */
5713 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005714 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005715 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005716 debug_printf_parse("parse_group return 1: "
5717 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005718 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005719 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005720#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005721
5722#if ENABLE_HUSH_FUNCTIONS
5723 skip:
5724#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005725 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005726 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005727 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005728 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005729 } else {
5730 /* bash does not allow "{echo...", requires whitespace */
5731 ch = i_getch(input);
5732 if (ch != ' ' && ch != '\t' && ch != '\n') {
5733 syntax_error_unexpected_ch(ch);
5734 return 1;
5735 }
5736 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005737 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005738
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005739 {
5740#if !BB_MMU
5741 char *as_string = NULL;
5742#endif
5743 pipe_list = parse_stream(&as_string, input, endch);
5744#if !BB_MMU
5745 if (as_string)
5746 o_addstr(&ctx->as_string, as_string);
5747#endif
5748 /* empty ()/{} or parse error? */
5749 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005750 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005751#if !BB_MMU
5752 free(as_string);
5753#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005754 debug_printf_parse("parse_group return 1: "
5755 "parse_stream returned %p\n", pipe_list);
5756 return 1;
5757 }
5758 command->group = pipe_list;
5759#if !BB_MMU
5760 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5761 command->group_as_string = as_string;
5762 debug_printf_parse("end of group, remembering as:'%s'\n",
5763 command->group_as_string);
5764#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005765 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005766 debug_printf_parse("parse_group return 0\n");
5767 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005768 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005769}
5770
Mike Frysinger98c52642009-04-02 10:02:37 +00005771#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005772/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005773static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005774/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005775static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005776{
5777 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005778 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005779 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005780 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005781 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005782 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005783 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005784 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005785 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005786 }
5787}
5788/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005789static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005790{
5791 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005792 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005793 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005794 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005795 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005796 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005797 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005798 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005799 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005800 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005801 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005802 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005803 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005804 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005805 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005806 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005807 continue;
5808 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005809 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005810 }
5811}
5812/* Process `cmd` - copy contents until "`" is seen. Complicated by
5813 * \` quoting.
5814 * "Within the backquoted style of command substitution, backslash
5815 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5816 * The search for the matching backquote shall be satisfied by the first
5817 * backquote found without a preceding backslash; during this search,
5818 * if a non-escaped backquote is encountered within a shell comment,
5819 * a here-document, an embedded command substitution of the $(command)
5820 * form, or a quoted string, undefined results occur. A single-quoted
5821 * or double-quoted string that begins, but does not end, within the
5822 * "`...`" sequence produces undefined results."
5823 * Example Output
5824 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5825 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005826static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005827{
5828 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005829 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005830 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005831 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005832 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005833 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005834 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005835 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005836 if (ch == '\\') {
5837 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005838 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005839 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005840 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005841 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005842 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005843 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005844 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005845 ch = ch2;
5846 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005847 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005848 }
5849}
5850/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5851 * quoting and nested ()s.
5852 * "With the $(command) style of command substitution, all characters
5853 * following the open parenthesis to the matching closing parenthesis
5854 * constitute the command. Any valid shell script can be used for command,
5855 * except a script consisting solely of redirections which produces
5856 * unspecified results."
5857 * Example Output
5858 * echo $(echo '(TEST)' BEST) (TEST) BEST
5859 * echo $(echo 'TEST)' BEST) TEST) BEST
5860 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5861 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005862static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005863{
5864 int count = 0;
5865 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005866 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005867 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005868 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005869 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005870 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005871 if (ch == '(')
5872 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005873 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005874 if (--count < 0) {
5875 if (!dbl)
5876 break;
5877 if (i_peek(input) == ')') {
5878 i_getch(input);
5879 break;
5880 }
5881 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005882 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005883 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005884 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005885 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005886 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005887 continue;
5888 }
5889 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005890 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005891 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005892 continue;
5893 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005894 if (ch == '\\') {
5895 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005896 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005897 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005898 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005899 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005900 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005901 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005902 continue;
5903 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005904 }
5905}
Mike Frysinger98c52642009-04-02 10:02:37 +00005906#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005907
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005908/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005909#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005910#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005911 handle_dollar(dest, input)
5912#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005913static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005914 o_string *dest,
5915 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005916{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005917 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005918 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005919
5920 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005921 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005922 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005923 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005924 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005925 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005926 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005927 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005928 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005929 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005930 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005931 if (!isalnum(ch) && ch != '_')
5932 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005933 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005934 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005935 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005936 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005937 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005938 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005939 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005940 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005941 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005942 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005943 o_addchr(dest, ch | quote_mask);
5944 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005945 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005946 case '$': /* pid */
5947 case '!': /* last bg pid */
5948 case '?': /* last exit code */
5949 case '#': /* number of args */
5950 case '*': /* args */
5951 case '@': /* args */
5952 goto make_one_char_var;
5953 case '{': {
5954 bool first_char, all_digits;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02005955 bool in_expansion_param;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005956
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005957 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005958 nommu_addchr(as_string, ch);
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005959 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5960
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02005961// TODO: need to handle "a=ab}; echo ${a%\}}"
5962// and "a=abc; c=c; echo ${a%${c}}"
5963 in_expansion_param = false;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005964 first_char = true;
5965 all_digits = false;
5966 while (1) {
5967 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005968 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005969 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005970 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005971 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005972
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005973 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005974 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005975 /* ${#var}: length of var contents */
5976 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005977 }
5978 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005979 all_digits = true;
5980 goto char_ok;
5981 }
Mike Frysingerdc3bc402009-06-01 14:09:09 -04005982 /* They're being verbose and doing ${?} */
5983 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5984 goto char_ok;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005985 }
5986
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02005987 if (!in_expansion_param
5988 && ( (all_digits && !isdigit(ch)) /* met non-digit: 123w */
5989 || (!all_digits && !isalnum(ch) && ch != '_') /* met non-name char: abc% */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005990 )
5991 ) {
5992 /* handle parameter expansions
5993 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5994 */
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02005995 if (first_char /* bad (empty var name): "${%..." */
5996 || !strchr("%#:-=+?", ch) /* bad: "${var<bad_char>..." */
5997 ) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005998 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005999 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
6000 return 1;
6001 }
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02006002 in_expansion_param = true;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006003 }
6004 char_ok:
6005 debug_printf_parse(": '%c'\n", ch);
6006 o_addchr(dest, ch | quote_mask);
6007 quote_mask = 0;
6008 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006009 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006010 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6011 break;
6012 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006013#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006014 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006015# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006016 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006017# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006018 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006019 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006020# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006021 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006022 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006023 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006024 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6025 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006026# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006027 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006028# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006029 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006030# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006031 if (as_string) {
6032 o_addstr(as_string, dest->data + pos);
6033 o_addchr(as_string, ')');
6034 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006035 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006036# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006037 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006038 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006039 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006040# endif
6041# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006042 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6043 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006044# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006045 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006046# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006047 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006048# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006049 if (as_string) {
6050 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006051 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006052 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006053# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006054 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006055# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006056 break;
6057 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006058#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006059 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006060 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006061 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006062 ch = i_peek(input);
6063 if (isalnum(ch)) { /* it's $_name or $_123 */
6064 ch = '_';
6065 goto make_var;
6066 }
6067 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02006068 /* TODO: $_ and $-: */
6069 /* $_ Shell or shell script name; or last argument of last command
6070 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6071 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006072 /* $- Option flags set by set builtin or shell options (-i etc) */
6073 default:
6074 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00006075 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006076 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00006077 return 0;
6078}
6079
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006080#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006081#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006082 parse_stream_dquoted(dest, input, dquote_end)
6083#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006084static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006085 o_string *dest,
6086 struct in_str *input,
6087 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006088{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006089 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006090 int next;
6091
6092 again:
6093 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006094 if (ch != EOF)
6095 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006096 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006097 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006098 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006099 debug_printf_parse("parse_stream_dquoted return 0\n");
6100 return 0;
6101 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006102 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006103 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006104 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006105 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006106 }
6107 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006108 if (ch != '\n') {
6109 next = i_peek(input);
6110 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006111 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006112 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006113 if (ch == '\\') {
6114 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006115 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006116 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006117 }
6118 /* bash:
6119 * "The backslash retains its special meaning [in "..."]
6120 * only when followed by one of the following characters:
6121 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006122 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006123 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006124 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00006125 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006126 if (ch != '\n') {
6127 o_addqchr(dest, ch);
6128 nommu_addchr(as_string, ch);
6129 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006130 } else {
6131 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00006132 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006133 }
6134 goto again;
6135 }
6136 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006137 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006138 debug_printf_parse("parse_stream_dquoted return 1: "
6139 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006140 return 1;
6141 }
6142 goto again;
6143 }
6144#if ENABLE_HUSH_TICK
6145 if (ch == '`') {
6146 //int pos = dest->length;
6147 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6148 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006149 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006150 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6151 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00006152 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006153 }
6154#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00006155 o_addQchr(dest, ch);
6156 if (ch == '='
6157 && (dest->o_assignment == MAYBE_ASSIGNMENT
6158 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006159 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00006160 ) {
6161 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6162 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006163 goto again;
6164}
6165
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006166/*
6167 * Scan input until EOF or end_trigger char.
6168 * Return a list of pipes to execute, or NULL on EOF
6169 * or if end_trigger character is met.
6170 * On syntax error, exit is shell is not interactive,
6171 * reset parsing machinery and start parsing anew,
6172 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006173 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006174static struct pipe *parse_stream(char **pstring,
6175 struct in_str *input,
6176 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006177{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006178 struct parse_context ctx;
6179 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006180 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006181 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006182
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006183 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006184 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006185 * found. When recursing, quote state is passed in via dest->o_escape.
6186 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006187 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006188 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006189 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006190
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006191 /* If very first arg is "" or '', dest.data may end up NULL.
6192 * Preventing this: */
6193 o_addchr(&dest, '\0');
6194 dest.length = 0;
6195
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006196 G.ifs = get_local_var_value("IFS");
6197 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01006198 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006199
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006200 reset:
6201#if ENABLE_HUSH_INTERACTIVE
6202 input->promptmode = 0; /* PS1 */
6203#endif
6204 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6205 initialize_context(&ctx);
6206 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006207 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006208 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006209 const char *is_ifs;
6210 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006211 int ch;
6212 int next;
6213 int redir_fd;
6214 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006215
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006216 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006217 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006218 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006219 goto parse_error;
6220 }
6221 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006222 is_in_dquote = 0;
6223 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006224 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006225 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6226 ch, ch, dest.o_escape);
6227 if (ch == EOF) {
6228 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006229
6230 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006231 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006232 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006233 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006234 /* end_trigger == '}' case errors out earlier,
6235 * checking only ')' */
6236 if (end_trigger == ')') {
6237 syntax_error_unterm_ch('('); /* exits */
6238 /* goto parse_error; */
6239 }
6240
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006241 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006242 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006243 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006244 o_free(&dest);
6245 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006246 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006247 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006248 /* (this makes bare "&" cmd a no-op.
6249 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006250 if (pi->num_cmds == 0
6251 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6252 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006253 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006254 pi = NULL;
6255 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006256#if !BB_MMU
6257 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6258 if (pstring)
6259 *pstring = ctx.as_string.data;
6260 else
6261 o_free_unsafe(&ctx.as_string);
6262#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006263 debug_leave();
6264 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006265 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006266 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006267 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006268
6269 next = '\0';
6270 if (ch != '\n')
6271 next = i_peek(input);
6272
6273 is_special = "{}<>;&|()#'" /* special outside of "str" */
6274 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6275 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02006276 if (ctx.command->argv /* word [word]{... - non-special */
6277 || dest.length /* word{... - non-special */
6278 || dest.o_quoted /* ""{... - non-special */
6279 || (next != ';' /* }; - special */
6280 && next != ')' /* }) - special */
6281 && next != '&' /* }& and }&& ... - special */
6282 && next != '|' /* }|| ... - special */
6283 && !strchr(G.ifs, next) /* {word - non-special */
6284 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006285 ) {
6286 /* They are not special, skip "{}" */
6287 is_special += 2;
6288 }
6289 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006290 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006291
6292 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006293 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006294 o_addQchr(&dest, ch);
6295 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6296 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006297 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006298 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006299 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006300 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006301 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006302 continue;
6303 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006304
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006305 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006306 if (done_word(&dest, &ctx)) {
6307 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006308 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006309 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006310#if ENABLE_HUSH_CASE
6311 /* "case ... in <newline> word) ..." -
6312 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006313 if (ctx.command->argv == NULL
6314 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006315 ) {
6316 continue;
6317 }
6318#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006319 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006320 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006321 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6322 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006323 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006324 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006325 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006326 heredoc_cnt = 0;
6327 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006328 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006329 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006330 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006331 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006332 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006333 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006334
6335 /* "cmd}" or "cmd }..." without semicolon or &:
6336 * } is an ordinary char in this case, even inside { cmd; }
6337 * Pathological example: { ""}; } should exec "}" cmd
6338 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006339 if (ch == '}') {
6340 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6341 || dest.length != 0 /* word} */
6342 || dest.o_quoted /* ""} */
6343 ) {
6344 goto ordinary_char;
6345 }
6346 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6347 goto skip_end_trigger;
6348 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006349 }
6350
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006351 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006352 && (ch != ';' || heredoc_cnt == 0)
6353#if ENABLE_HUSH_CASE
6354 && (ch != ')'
6355 || ctx.ctx_res_w != RES_MATCH
6356 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6357 )
6358#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006359 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006360 if (heredoc_cnt) {
6361 /* This is technically valid:
6362 * { cat <<HERE; }; echo Ok
6363 * heredoc
6364 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006365 * HERE
6366 * but we don't support this.
6367 * We require heredoc to be in enclosing {}/(),
6368 * if any.
6369 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006370 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006371 goto parse_error;
6372 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006373 if (done_word(&dest, &ctx)) {
6374 goto parse_error;
6375 }
6376 done_pipe(&ctx, PIPE_SEQ);
6377 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006378 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006379 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006380 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006381 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006382 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006383#if !BB_MMU
6384 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6385 if (pstring)
6386 *pstring = ctx.as_string.data;
6387 else
6388 o_free_unsafe(&ctx.as_string);
6389#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006390 debug_leave();
6391 debug_printf_parse("parse_stream return %p: "
6392 "end_trigger char found\n",
6393 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006394 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006395 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006396 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006397 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006398 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006399 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006400
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006401 /* Catch <, > before deciding whether this word is
6402 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6403 switch (ch) {
6404 case '>':
6405 redir_fd = redirect_opt_num(&dest);
6406 if (done_word(&dest, &ctx)) {
6407 goto parse_error;
6408 }
6409 redir_style = REDIRECT_OVERWRITE;
6410 if (next == '>') {
6411 redir_style = REDIRECT_APPEND;
6412 ch = i_getch(input);
6413 nommu_addchr(&ctx.as_string, ch);
6414 }
6415#if 0
6416 else if (next == '(') {
6417 syntax_error(">(process) not supported");
6418 goto parse_error;
6419 }
6420#endif
6421 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6422 goto parse_error;
6423 continue; /* back to top of while (1) */
6424 case '<':
6425 redir_fd = redirect_opt_num(&dest);
6426 if (done_word(&dest, &ctx)) {
6427 goto parse_error;
6428 }
6429 redir_style = REDIRECT_INPUT;
6430 if (next == '<') {
6431 redir_style = REDIRECT_HEREDOC;
6432 heredoc_cnt++;
6433 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6434 ch = i_getch(input);
6435 nommu_addchr(&ctx.as_string, ch);
6436 } else if (next == '>') {
6437 redir_style = REDIRECT_IO;
6438 ch = i_getch(input);
6439 nommu_addchr(&ctx.as_string, ch);
6440 }
6441#if 0
6442 else if (next == '(') {
6443 syntax_error("<(process) not supported");
6444 goto parse_error;
6445 }
6446#endif
6447 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6448 goto parse_error;
6449 continue; /* back to top of while (1) */
6450 }
6451
6452 if (dest.o_assignment == MAYBE_ASSIGNMENT
6453 /* check that we are not in word in "a=1 2>word b=1": */
6454 && !ctx.pending_redirect
6455 ) {
6456 /* ch is a special char and thus this word
6457 * cannot be an assignment */
6458 dest.o_assignment = NOT_ASSIGNMENT;
6459 }
6460
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006461 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6462
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006463 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006464 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006465 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006466 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006467 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006468 if (ch == EOF || ch == '\n')
6469 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006470 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006471 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006472 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006473 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006474 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006475 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006476 }
6477 break;
6478 case '\\':
6479 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006480 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006481 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006482 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006483 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006484 if (ch != '\n') {
6485 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006486 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006487 o_addchr(&dest, ch);
6488 nommu_addchr(&ctx.as_string, ch);
6489 /* Example: echo Hello \2>file
6490 * we need to know that word 2 is quoted */
6491 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006492 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006493#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006494 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006495 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6496 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006497 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006498#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006499 break;
6500 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006501 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006502 debug_printf_parse("parse_stream parse error: "
6503 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006504 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006505 }
Eric Andersen25f27032001-04-26 23:22:31 +00006506 break;
6507 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006508 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006509 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006510 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006511 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006512 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006513 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006514 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006515 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006516 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006517 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006518 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006519 }
Eric Andersen25f27032001-04-26 23:22:31 +00006520 break;
6521 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006522 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006523 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006524 if (dest.o_assignment == NOT_ASSIGNMENT)
6525 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006526 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006527#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006528 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006529#if !BB_MMU
6530 int pos;
6531#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006532 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6533 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006534#if !BB_MMU
6535 pos = dest.length;
6536#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006537 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006538#if !BB_MMU
6539 o_addstr(&ctx.as_string, dest.data + pos);
6540 o_addchr(&ctx.as_string, '`');
6541#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006542 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6543 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006544 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006545 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006546#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006547 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006548#if ENABLE_HUSH_CASE
6549 case_semi:
6550#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006551 if (done_word(&dest, &ctx)) {
6552 goto parse_error;
6553 }
6554 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006555#if ENABLE_HUSH_CASE
6556 /* Eat multiple semicolons, detect
6557 * whether it means something special */
6558 while (1) {
6559 ch = i_peek(input);
6560 if (ch != ';')
6561 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006562 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006563 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006564 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006565 ctx.ctx_dsemicolon = 1;
6566 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006567 break;
6568 }
6569 }
6570#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006571 new_cmd:
6572 /* We just finished a cmd. New one may start
6573 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006574 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006575 break;
6576 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006577 if (done_word(&dest, &ctx)) {
6578 goto parse_error;
6579 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006580 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006581 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006582 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006583 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006584 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006585 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006586 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006587 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006588 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006589 if (done_word(&dest, &ctx)) {
6590 goto parse_error;
6591 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006592#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006593 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006594 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006595#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006596 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006597 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006598 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006599 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006600 } else {
6601 /* we could pick up a file descriptor choice here
6602 * with redirect_opt_num(), but bash doesn't do it.
6603 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006604 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006605#if !BB_MMU
6606 o_reset_to_empty_unquoted(&ctx.as_string);
6607#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006608 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006609 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006610 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006611#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006612 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006613 if (ctx.ctx_res_w == RES_MATCH
6614 && ctx.command->argv == NULL /* not (word|(... */
6615 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006616 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006617 ) {
6618 continue;
6619 }
6620#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006621 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006622 if (parse_group(&dest, &ctx, input, ch) != 0) {
6623 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006624 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006625 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006626 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006627#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006628 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006629 goto case_semi;
6630#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006631 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006632 /* proper use of this character is caught by end_trigger:
6633 * if we see {, we call parse_group(..., end_trigger='}')
6634 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006635 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006636 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006637 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006638 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006639 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006640 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006641 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006642
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006643 parse_error:
6644 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006645 struct parse_context *pctx;
6646 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006647
6648 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006649 * Sample for finding leaks on syntax error recovery path.
6650 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006651 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006652 * Samples to catch leaks at execution:
6653 * while if (true | {true;}); then echo ok; fi; do break; done
6654 * 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 +00006655 */
6656 pctx = &ctx;
6657 do {
6658 /* Update pipe/command counts,
6659 * otherwise freeing may miss some */
6660 done_pipe(pctx, PIPE_SEQ);
6661 debug_printf_clean("freeing list %p from ctx %p\n",
6662 pctx->list_head, pctx);
6663 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006664 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006665 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006666#if !BB_MMU
6667 o_free_unsafe(&pctx->as_string);
6668#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006669 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006670 if (pctx != &ctx) {
6671 free(pctx);
6672 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006673 IF_HAS_KEYWORDS(pctx = p2;)
6674 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006675 /* Free text, clear all dest fields */
6676 o_free(&dest);
6677 /* If we are not in top-level parse, we return,
6678 * our caller will propagate error.
6679 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006680 if (end_trigger != ';') {
6681#if !BB_MMU
6682 if (pstring)
6683 *pstring = NULL;
6684#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006685 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006686 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006687 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006688 /* Discard cached input, force prompt */
6689 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006690 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006691 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006692 }
Eric Andersen25f27032001-04-26 23:22:31 +00006693}
6694
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006695/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006696 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6697 * end_trigger controls how often we stop parsing
6698 * NUL: parse all, execute, return
6699 * ';': parse till ';' or newline, execute, repeat till EOF
6700 */
6701static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006702{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006703 /* Why we need empty flag?
6704 * An obscure corner case "false; ``; echo $?":
6705 * empty command in `` should still set $? to 0.
6706 * But we can't just set $? to 0 at the start,
6707 * this breaks "false; echo `echo $?`" case.
6708 */
6709 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006710 while (1) {
6711 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006712
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006713 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006714 if (!pipe_list) { /* EOF */
6715 if (empty)
6716 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006717 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006718 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006719 debug_print_tree(pipe_list, 0);
6720 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6721 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006722 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006723 }
Eric Andersen25f27032001-04-26 23:22:31 +00006724}
6725
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006726static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006727{
6728 struct in_str input;
6729 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006730 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006731}
6732
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006733static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006734{
Eric Andersen25f27032001-04-26 23:22:31 +00006735 struct in_str input;
6736 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006737 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006738}
6739
Denis Vlasenkof9375282009-04-05 19:13:39 +00006740/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006741static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006742{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006743 unsigned sig;
6744 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006745 sigset_t old_blocked_set;
6746
6747 if (!G.inherited_set_is_saved) {
6748 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6749 G.inherited_set = G.blocked_set;
6750 }
6751 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006752
Denis Vlasenkof9375282009-04-05 19:13:39 +00006753 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006754 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006755 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006756 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006757 mask |= SPECIAL_JOB_SIGS;
6758 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006759 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006760
Denis Vlasenkof9375282009-04-05 19:13:39 +00006761 sig = 0;
6762 while (mask) {
6763 if (mask & 1)
6764 sigaddset(&G.blocked_set, sig);
6765 mask >>= 1;
6766 sig++;
6767 }
6768 sigdelset(&G.blocked_set, SIGCHLD);
6769
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006770 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
6771 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6772
Denis Vlasenkof9375282009-04-05 19:13:39 +00006773 /* POSIX allows shell to re-enable SIGCHLD
6774 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006775#if ENABLE_HUSH_FAST
6776 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006777 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006778 signal(SIGCHLD, SIGCHLD_handler);
6779#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006780 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006781 signal(SIGCHLD, SIG_DFL);
6782#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006783
6784 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00006785}
6786
6787#if ENABLE_HUSH_JOB
6788/* helper */
6789static void maybe_set_to_sigexit(int sig)
6790{
6791 void (*handler)(int);
6792 /* non_DFL_mask'ed signals are, well, masked,
6793 * no need to set handler for them.
6794 */
6795 if (!((G.non_DFL_mask >> sig) & 1)) {
6796 handler = signal(sig, sigexit);
6797 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6798 signal(sig, handler);
6799 }
6800}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006801/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006802static void set_fatal_handlers(void)
6803{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006804 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006805 if (HUSH_DEBUG) {
6806 maybe_set_to_sigexit(SIGILL );
6807 maybe_set_to_sigexit(SIGFPE );
6808 maybe_set_to_sigexit(SIGBUS );
6809 maybe_set_to_sigexit(SIGSEGV);
6810 maybe_set_to_sigexit(SIGTRAP);
6811 } /* else: hush is perfect. what SEGV? */
6812 maybe_set_to_sigexit(SIGABRT);
6813 /* bash 3.2 seems to handle these just like 'fatal' ones */
6814 maybe_set_to_sigexit(SIGPIPE);
6815 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006816 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006817 * if we aren't interactive... but in this case
6818 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006819 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006820 /*maybe_set_to_sigexit(SIGTERM);*/
6821 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006822}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006823#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006824
Denis Vlasenkod5762932009-03-31 11:22:57 +00006825static int set_mode(const char cstate, const char mode)
6826{
6827 int state = (cstate == '-' ? 1 : 0);
6828 switch (mode) {
6829 case 'n': G.fake_mode = state; break;
6830 case 'x': /*G.debug_mode = state;*/ break;
6831 default: return EXIT_FAILURE;
6832 }
6833 return EXIT_SUCCESS;
6834}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006835
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006836int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006837int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006838{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006839 static const struct variable const_shell_ver = {
6840 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006841 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006842 .max_len = 1, /* 0 can provoke free(name) */
6843 .flg_export = 1,
6844 .flg_read_only = 1,
6845 };
Eric Andersen25f27032001-04-26 23:22:31 +00006846 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006847 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006848 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006849 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006850
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006851 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02006852 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006853 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006854#if !BB_MMU
6855 G.argv0_for_re_execing = argv[0];
6856#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006857 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006858 G.shell_ver = const_shell_ver; /* copying struct here */
6859 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006860 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006861 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6862 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006863 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006864 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006865 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006866 if (e) while (*e) {
6867 char *value = strchr(*e, '=');
6868 if (value) { /* paranoia */
6869 cur_var->next = xzalloc(sizeof(*cur_var));
6870 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006871 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006872 cur_var->max_len = strlen(*e);
6873 cur_var->flg_export = 1;
6874 }
6875 e++;
6876 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006877 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006878 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02006879 putenv((char *)hush_version_str);
6880
6881 /* Export PWD */
6882 set_pwd_var(/*exp:*/ 1);
6883 /* bash also exports SHLVL and _,
6884 * and sets (but doesn't export) the following variables:
6885 * BASH=/bin/bash
6886 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6887 * BASH_VERSION='3.2.0(1)-release'
6888 * HOSTTYPE=i386
6889 * MACHTYPE=i386-pc-linux-gnu
6890 * OSTYPE=linux-gnu
6891 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02006892 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02006893 * EUID=<NNNNN>
6894 * UID=<NNNNN>
6895 * GROUPS=()
6896 * LINES=<NNN>
6897 * COLUMNS=<NNN>
6898 * BASH_ARGC=()
6899 * BASH_ARGV=()
6900 * BASH_LINENO=()
6901 * BASH_SOURCE=()
6902 * DIRSTACK=()
6903 * PIPESTATUS=([0]="0")
6904 * HISTFILE=/<xxx>/.bash_history
6905 * HISTFILESIZE=500
6906 * HISTSIZE=500
6907 * MAILCHECK=60
6908 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6909 * SHELL=/bin/bash
6910 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6911 * TERM=dumb
6912 * OPTERR=1
6913 * OPTIND=1
6914 * IFS=$' \t\n'
6915 * PS1='\s-\v\$ '
6916 * PS2='> '
6917 * PS4='+ '
6918 */
6919
Denis Vlasenko38f63192007-01-22 09:03:07 +00006920#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006921 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006922#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006923 G.global_argc = argc;
6924 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006925 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006926 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006927
Denis Vlasenkoed782372009-04-10 00:45:02 +00006928 if (setjmp(die_jmp)) {
6929 /* xfunc has failed! die die die */
6930 /* no EXIT traps, this is an escape hatch! */
6931 G.exiting = 1;
6932 hush_exit(xfunc_error_retval);
6933 }
6934
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006935 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006936 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006937 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006938 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006939 * in order to intercept (more) signals.
6940 */
6941
6942 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006943 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006944 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006945 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02006946 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006947#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006948 "<:$:R:V:"
6949# if ENABLE_HUSH_FUNCTIONS
6950 "F:"
6951# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006952#endif
6953 );
6954 if (opt <= 0)
6955 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006956 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006957 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006958 /* Possibilities:
6959 * sh ... -c 'script'
6960 * sh ... -c 'script' ARG0 [ARG1...]
6961 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01006962 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006963 * "" needs to be replaced with NULL
6964 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01006965 * Note: the form without ARG0 never happens:
6966 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006967 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02006968 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006969 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02006970 G.root_ppid = getppid();
6971 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006972 G.global_argv = argv + optind;
6973 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006974 if (builtin_argc) {
6975 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6976 const struct built_in_command *x;
6977
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006978 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006979 x = find_builtin(optarg);
6980 if (x) { /* paranoia */
6981 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6982 G.global_argv += builtin_argc;
6983 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01006984 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006985 }
6986 goto final_return;
6987 }
6988 if (!G.global_argv[0]) {
6989 /* -c 'script' (no params): prevent empty $0 */
6990 G.global_argv--; /* points to argv[i] of 'script' */
6991 G.global_argv[0] = argv[0];
6992 G.global_argc--;
6993 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01006994 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006995 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006996 goto final_return;
6997 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00006998 /* Well, we cannot just declare interactiveness,
6999 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007000 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007001 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007002 case 's':
7003 /* "-s" means "read from stdin", but this is how we always
7004 * operate, so simply do nothing here. */
7005 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007006#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007007 case '<': /* "big heredoc" support */
7008 full_write(STDOUT_FILENO, optarg, strlen(optarg));
7009 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007010 case '$': {
7011 unsigned long long empty_trap_mask;
7012
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007013 G.root_pid = bb_strtou(optarg, &optarg, 16);
7014 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007015 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7016 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007017 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7018 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007019 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007020 optarg++;
7021 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007022 optarg++;
7023 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7024 if (empty_trap_mask != 0) {
7025 int sig;
7026 init_sigmasks();
7027 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7028 for (sig = 1; sig < NSIG; sig++) {
7029 if (empty_trap_mask & (1LL << sig)) {
7030 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7031 sigaddset(&G.blocked_set, sig);
7032 }
7033 }
7034 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7035 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007036# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007037 optarg++;
7038 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007039# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007040 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007041 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007042 case 'R':
7043 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007044 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007045 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007046# if ENABLE_HUSH_FUNCTIONS
7047 case 'F': {
7048 struct function *funcp = new_function(optarg);
7049 /* funcp->name is already set to optarg */
7050 /* funcp->body is set to NULL. It's a special case. */
7051 funcp->body_as_string = argv[optind];
7052 optind++;
7053 break;
7054 }
7055# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007056#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007057 case 'n':
7058 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00007059 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007060 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007061 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007062#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007063 fprintf(stderr, "Usage: sh [FILE]...\n"
7064 " or: sh -c command [args]...\n\n");
7065 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007066#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007067 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007068#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007069 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007070 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007071
Denys Vlasenkodea47882009-10-09 15:40:49 +02007072 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007073 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007074 G.root_ppid = getppid();
7075 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007076
7077 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007078 if (argv[0] && argv[0][0] == '-') {
7079 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007080 debug_printf("sourcing /etc/profile\n");
7081 input = fopen_for_read("/etc/profile");
7082 if (input != NULL) {
7083 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007084 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007085 parse_and_run_file(input);
7086 fclose(input);
7087 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007088 /* bash: after sourcing /etc/profile,
7089 * tries to source (in the given order):
7090 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007091 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007092 * bash also sources ~/.bash_logout on exit.
7093 * If called as sh, skips .bash_XXX files.
7094 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007095 }
7096
Denis Vlasenkof9375282009-04-05 19:13:39 +00007097 if (argv[optind]) {
7098 FILE *input;
7099 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007100 * "bash <script>" (which is never interactive (unless -i?))
7101 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007102 * If called as sh, does the same but with $ENV.
7103 */
7104 debug_printf("running script '%s'\n", argv[optind]);
7105 G.global_argv = argv + optind;
7106 G.global_argc = argc - optind;
7107 input = xfopen_for_read(argv[optind]);
7108 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007109 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007110 parse_and_run_file(input);
7111#if ENABLE_FEATURE_CLEAN_UP
7112 fclose(input);
7113#endif
7114 goto final_return;
7115 }
7116
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007117 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007118 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007119 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007120
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007121 /* A shell is interactive if the '-i' flag was given,
7122 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007123 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007124 * no arguments remaining or the -s flag given
7125 * standard input is a terminal
7126 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007127 * Refer to Posix.2, the description of the 'sh' utility.
7128 */
7129#if ENABLE_HUSH_JOB
7130 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007131 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7132 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7133 if (G_saved_tty_pgrp < 0)
7134 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007135
7136 /* try to dup stdin to high fd#, >= 255 */
7137 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7138 if (G_interactive_fd < 0) {
7139 /* try to dup to any fd */
7140 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007141 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007142 /* give up */
7143 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007144 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007145 }
7146 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007147// TODO: track & disallow any attempts of user
7148// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007149 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007150 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007151 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007152 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007153
Mike Frysinger38478a62009-05-20 04:48:06 -04007154 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007155 /* If we were run as 'hush &', sleep until we are
7156 * in the foreground (tty pgrp == our pgrp).
7157 * If we get started under a job aware app (like bash),
7158 * make sure we are now in charge so we don't fight over
7159 * who gets the foreground */
7160 while (1) {
7161 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007162 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7163 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007164 break;
7165 /* send TTIN to ourself (should stop us) */
7166 kill(- shell_pgrp, SIGTTIN);
7167 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007168 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007169
Denis Vlasenkof9375282009-04-05 19:13:39 +00007170 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007171 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007172
Mike Frysinger38478a62009-05-20 04:48:06 -04007173 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007174 /* Set other signals to restore saved_tty_pgrp */
7175 set_fatal_handlers();
7176 /* Put ourselves in our own process group
7177 * (bash, too, does this only if ctty is available) */
7178 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7179 /* Grab control of the terminal */
7180 tcsetpgrp(G_interactive_fd, getpid());
7181 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007182 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007183 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007184 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007185 } else {
7186 init_sigmasks();
7187 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007188#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007189 /* No job control compiled in, only prompt/line editing */
7190 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007191 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7192 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007193 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007194 G_interactive_fd = dup(STDIN_FILENO);
7195 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007196 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007197 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007198 }
7199 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007200 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007201 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007202 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007203 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007204#else
7205 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007206 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007207#endif
7208 /* bash:
7209 * if interactive but not a login shell, sources ~/.bashrc
7210 * (--norc turns this off, --rcfile <file> overrides)
7211 */
7212
7213 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007214 /* note: ash and hush share this string */
7215 printf("\n\n%s %s\n"
7216 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7217 "\n",
7218 bb_banner,
7219 "hush - the humble shell"
7220 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007221 }
7222
Denis Vlasenkof9375282009-04-05 19:13:39 +00007223 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007224
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007225 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007226#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007227 if (G.cwd != bb_msg_unknown)
7228 free((char*)G.cwd);
7229 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007230 while (cur_var) {
7231 struct variable *tmp = cur_var;
7232 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007233 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007234 cur_var = cur_var->next;
7235 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007236 }
Eric Andersen25f27032001-04-26 23:22:31 +00007237#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007238 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007239}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007240
7241
7242#if ENABLE_LASH
7243int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7244int lash_main(int argc, char **argv)
7245{
Denys Vlasenko07934912009-08-20 03:40:04 +02007246 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007247 return hush_main(argc, argv);
7248}
7249#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007250
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007251#if ENABLE_MSH
7252int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7253int msh_main(int argc, char **argv)
7254{
7255 //bb_error_msg("msh is deprecated, please use hush instead");
7256 return hush_main(argc, argv);
7257}
7258#endif
7259
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007260
7261/*
7262 * Built-ins
7263 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007264static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007265{
7266 return 0;
7267}
7268
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007269static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007270{
7271 int argc = 0;
7272 while (*argv) {
7273 argc++;
7274 argv++;
7275 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007276 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007277}
7278
7279static int FAST_FUNC builtin_test(char **argv)
7280{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007281 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007282}
7283
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007284static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007285{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007286 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007287}
7288
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007289#if ENABLE_PRINTF
7290static int FAST_FUNC builtin_printf(char **argv)
7291{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007292 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007293}
7294#endif
7295
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007296static char **skip_dash_dash(char **argv)
7297{
7298 argv++;
7299 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7300 argv++;
7301 return argv;
7302}
7303
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007304static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007305{
7306 int rcode = EXIT_SUCCESS;
7307
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007308 argv = skip_dash_dash(argv);
7309 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007310 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007311 /* bash:
7312 * eval "echo Hi; done" ("done" is syntax error):
7313 * "echo Hi" will not execute too.
7314 */
7315 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007316 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007317 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007318 }
7319 return rcode;
7320}
7321
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007322static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007323{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007324 const char *newdir;
7325
7326 argv = skip_dash_dash(argv);
7327 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007328 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007329 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007330 * bash says "bash: cd: HOME not set" and does nothing
7331 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007332 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007333 const char *home = get_local_var_value("HOME");
7334 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007335 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007336 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007337 /* Mimic bash message exactly */
7338 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007339 return EXIT_FAILURE;
7340 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007341 /* Read current dir (get_cwd(1) is inside) and set PWD.
7342 * Note: do not enforce exporting. If PWD was unset or unexported,
7343 * set it again, but do not export. bash does the same.
7344 */
7345 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007346 return EXIT_SUCCESS;
7347}
7348
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007349static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007350{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007351 argv = skip_dash_dash(argv);
7352 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007353 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007354
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007355 /* Careful: we can end up here after [v]fork. Do not restore
7356 * tty pgrp then, only top-level shell process does that */
7357 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7358 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7359
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007360 /* TODO: if exec fails, bash does NOT exit! We do.
7361 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7362 * and tcsetpgrp, and this is inherently racy.
7363 */
7364 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007365}
7366
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007367static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007368{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007369 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007370
7371 /* interactive bash:
7372 * # trap "echo EEE" EXIT
7373 * # exit
7374 * exit
7375 * There are stopped jobs.
7376 * (if there are _stopped_ jobs, running ones don't count)
7377 * # exit
7378 * exit
7379 # EEE (then bash exits)
7380 *
7381 * we can use G.exiting = -1 as indicator "last cmd was exit"
7382 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007383
7384 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007385 argv = skip_dash_dash(argv);
7386 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007387 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007388 /* mimic bash: exit 123abc == exit 255 + error msg */
7389 xfunc_error_retval = 255;
7390 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007391 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007392}
7393
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007394static void print_escaped(const char *s)
7395{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007396 if (*s == '\'')
7397 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007398 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007399 const char *p = strchrnul(s, '\'');
7400 /* print 'xxxx', possibly just '' */
7401 printf("'%.*s'", (int)(p - s), s);
7402 if (*p == '\0')
7403 break;
7404 s = p;
7405 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007406 /* s points to '; print "'''...'''" */
7407 putchar('"');
7408 do putchar('\''); while (*++s == '\'');
7409 putchar('"');
7410 } while (*s);
7411}
7412
Denys Vlasenko295fef82009-06-03 12:47:26 +02007413#if !ENABLE_HUSH_LOCAL
7414#define helper_export_local(argv, exp, lvl) \
7415 helper_export_local(argv, exp)
7416#endif
7417static void helper_export_local(char **argv, int exp, int lvl)
7418{
7419 do {
7420 char *name = *argv;
7421
7422 /* So far we do not check that name is valid (TODO?) */
7423
7424 if (strchr(name, '=') == NULL) {
7425 struct variable *var;
7426
7427 var = get_local_var(name);
7428 if (exp == -1) { /* unexporting? */
7429 /* export -n NAME (without =VALUE) */
7430 if (var) {
7431 var->flg_export = 0;
7432 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7433 unsetenv(name);
7434 } /* else: export -n NOT_EXISTING_VAR: no-op */
7435 continue;
7436 }
7437 if (exp == 1) { /* exporting? */
7438 /* export NAME (without =VALUE) */
7439 if (var) {
7440 var->flg_export = 1;
7441 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7442 putenv(var->varstr);
7443 continue;
7444 }
7445 }
7446 /* Exporting non-existing variable.
7447 * bash does not put it in environment,
7448 * but remembers that it is exported,
7449 * and does put it in env when it is set later.
7450 * We just set it to "" and export. */
7451 /* Or, it's "local NAME" (without =VALUE).
7452 * bash sets the value to "". */
7453 name = xasprintf("%s=", name);
7454 } else {
7455 /* (Un)exporting/making local NAME=VALUE */
7456 name = xstrdup(name);
7457 }
7458 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7459 } while (*++argv);
7460}
7461
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007462static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007463{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007464 unsigned opt_unexport;
7465
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007466#if ENABLE_HUSH_EXPORT_N
7467 /* "!": do not abort on errors */
7468 opt_unexport = getopt32(argv, "!n");
7469 if (opt_unexport == (uint32_t)-1)
7470 return EXIT_FAILURE;
7471 argv += optind;
7472#else
7473 opt_unexport = 0;
7474 argv++;
7475#endif
7476
7477 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007478 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007479 if (e) {
7480 while (*e) {
7481#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007482 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007483#else
7484 /* ash emits: export VAR='VAL'
7485 * bash: declare -x VAR="VAL"
7486 * we follow ash example */
7487 const char *s = *e++;
7488 const char *p = strchr(s, '=');
7489
7490 if (!p) /* wtf? take next variable */
7491 continue;
7492 /* export var= */
7493 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007494 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007495 putchar('\n');
7496#endif
7497 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007498 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007499 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007500 return EXIT_SUCCESS;
7501 }
7502
Denys Vlasenko295fef82009-06-03 12:47:26 +02007503 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007504
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007505 return EXIT_SUCCESS;
7506}
7507
Denys Vlasenko295fef82009-06-03 12:47:26 +02007508#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007509static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007510{
7511 if (G.func_nest_level == 0) {
7512 bb_error_msg("%s: not in a function", argv[0]);
7513 return EXIT_FAILURE; /* bash compat */
7514 }
7515 helper_export_local(argv, 0, G.func_nest_level);
7516 return EXIT_SUCCESS;
7517}
7518#endif
7519
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007520static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007521{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007522 int sig;
7523 char *new_cmd;
7524
7525 if (!G.traps)
7526 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7527
7528 argv++;
7529 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007530 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007531 /* No args: print all trapped */
7532 for (i = 0; i < NSIG; ++i) {
7533 if (G.traps[i]) {
7534 printf("trap -- ");
7535 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007536 /* note: bash adds "SIG", but only if invoked
7537 * as "bash". If called as "sh", or if set -o posix,
7538 * then it prints short signal names.
7539 * We are printing short names: */
7540 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007541 }
7542 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007543 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007544 return EXIT_SUCCESS;
7545 }
7546
7547 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007548 /* If first arg is a number: reset all specified signals */
7549 sig = bb_strtou(*argv, NULL, 10);
7550 if (errno == 0) {
7551 int ret;
7552 process_sig_list:
7553 ret = EXIT_SUCCESS;
7554 while (*argv) {
7555 sig = get_signum(*argv++);
7556 if (sig < 0 || sig >= NSIG) {
7557 ret = EXIT_FAILURE;
7558 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007559 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007560 continue;
7561 }
7562
7563 free(G.traps[sig]);
7564 G.traps[sig] = xstrdup(new_cmd);
7565
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007566 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007567 get_signame(sig), sig, G.traps[sig]);
7568
7569 /* There is no signal for 0 (EXIT) */
7570 if (sig == 0)
7571 continue;
7572
7573 if (new_cmd) {
7574 sigaddset(&G.blocked_set, sig);
7575 } else {
7576 /* There was a trap handler, we are removing it
7577 * (if sig has non-DFL handling,
7578 * we don't need to do anything) */
7579 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7580 continue;
7581 sigdelset(&G.blocked_set, sig);
7582 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007583 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007584 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007585 return ret;
7586 }
7587
7588 if (!argv[1]) { /* no second arg */
7589 bb_error_msg("trap: invalid arguments");
7590 return EXIT_FAILURE;
7591 }
7592
7593 /* First arg is "-": reset all specified to default */
7594 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7595 /* Everything else: set arg as signal handler
7596 * (includes "" case, which ignores signal) */
7597 if (argv[0][0] == '-') {
7598 if (argv[0][1] == '\0') { /* "-" */
7599 /* new_cmd remains NULL: "reset these sigs" */
7600 goto reset_traps;
7601 }
7602 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7603 argv++;
7604 }
7605 /* else: "-something", no special meaning */
7606 }
7607 new_cmd = *argv;
7608 reset_traps:
7609 argv++;
7610 goto process_sig_list;
7611}
7612
Mike Frysinger93cadc22009-05-27 17:06:25 -04007613/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007614static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007615{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007616 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007617
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007618 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007619 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007620 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007621
7622 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007623 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007624 type = "an alias";*/
7625#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007626 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007627 type = "a function";
7628#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007629 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007630 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007631 else if ((path = find_in_path(*argv)) != NULL)
7632 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007633 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007634 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007635 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007636 continue;
7637 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007638
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007639 printf("%s is %s\n", *argv, type);
7640 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007641 }
7642
7643 return ret;
7644}
7645
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007646#if ENABLE_HUSH_JOB
7647/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007648static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007649{
7650 int i, jobnum;
7651 struct pipe *pi;
7652
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007653 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007654 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007655
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007656 /* If they gave us no args, assume they want the last backgrounded task */
7657 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007658 for (pi = G.job_list; pi; pi = pi->next) {
7659 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007660 goto found;
7661 }
7662 }
7663 bb_error_msg("%s: no current job", argv[0]);
7664 return EXIT_FAILURE;
7665 }
7666 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7667 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7668 return EXIT_FAILURE;
7669 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007670 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007671 if (pi->jobid == jobnum) {
7672 goto found;
7673 }
7674 }
7675 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7676 return EXIT_FAILURE;
7677 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007678 /* TODO: bash prints a string representation
7679 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007680 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007681 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007682 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007683 }
7684
7685 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007686 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7687 for (i = 0; i < pi->num_cmds; i++) {
7688 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7689 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007690 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007691 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007692
7693 i = kill(- pi->pgrp, SIGCONT);
7694 if (i < 0) {
7695 if (errno == ESRCH) {
7696 delete_finished_bg_job(pi);
7697 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007698 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007699 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007700 }
7701
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007702 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007703 remove_bg_job(pi);
7704 return checkjobs_and_fg_shell(pi);
7705 }
7706 return EXIT_SUCCESS;
7707}
7708#endif
7709
7710#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007711static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007712{
7713 const struct built_in_command *x;
7714
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007715 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007716 "Built-in commands:\n"
7717 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007718 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01007719 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007720 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007721 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007722 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007723 return EXIT_SUCCESS;
7724}
7725#endif
7726
7727#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007728static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007729{
7730 struct pipe *job;
7731 const char *status_string;
7732
Denis Vlasenko87a86552008-07-29 19:43:10 +00007733 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007734 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007735 status_string = "Stopped";
7736 else
7737 status_string = "Running";
7738
7739 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7740 }
7741 return EXIT_SUCCESS;
7742}
7743#endif
7744
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007745#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007746static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007747{
7748 void *p;
7749 unsigned long l;
7750
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007751# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02007752 /* Optional. Reduces probability of false positives */
7753 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007754# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007755 /* Crude attempt to find where "free memory" starts,
7756 * sans fragmentation. */
7757 p = malloc(240);
7758 l = (unsigned long)p;
7759 free(p);
7760 p = malloc(3400);
7761 if (l < (unsigned long)p) l = (unsigned long)p;
7762 free(p);
7763
7764 if (!G.memleak_value)
7765 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007766
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007767 l -= G.memleak_value;
7768 if ((long)l < 0)
7769 l = 0;
7770 l /= 1024;
7771 if (l > 127)
7772 l = 127;
7773
7774 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7775 return l;
7776}
7777#endif
7778
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007779static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007780{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007781 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007782 return EXIT_SUCCESS;
7783}
7784
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007785static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007786{
Denys Vlasenko03dad222010-01-12 23:29:57 +01007787 const char *r;
7788 char *opt_n = NULL;
7789 char *opt_p = NULL;
7790 char *opt_t = NULL;
7791 char *opt_u = NULL;
7792 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007793
Denys Vlasenko03dad222010-01-12 23:29:57 +01007794 /* "!": do not abort on errors.
7795 * Option string must start with "sr" to match BUILTIN_READ_xxx
7796 */
7797 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
7798 if (read_flags == (uint32_t)-1)
7799 return EXIT_FAILURE;
7800 argv += optind;
7801
7802 r = shell_builtin_read(set_local_var_from_halves,
7803 argv,
7804 get_local_var_value("IFS"), /* can be NULL */
7805 read_flags,
7806 opt_n,
7807 opt_p,
7808 opt_t,
7809 opt_u
7810 );
7811
7812 if ((uintptr_t)r > 1) {
7813 bb_error_msg("%s", r);
7814 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007815 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007816
Denys Vlasenko03dad222010-01-12 23:29:57 +01007817 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007818}
7819
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007820/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7821 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007822 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007823 * set [-abCefhmnuvx] [-o option] [argument...]
7824 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007825 * set -- [argument...]
7826 * set -o
7827 * set +o
7828 * Implementations shall support the options in both their hyphen and
7829 * plus-sign forms. These options can also be specified as options to sh.
7830 * Examples:
7831 * Write out all variables and their values: set
7832 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7833 * Turn on the -x and -v options: set -xv
7834 * Unset all positional parameters: set --
7835 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7836 * Set the positional parameters to the expansion of x, even if x expands
7837 * with a leading '-' or '+': set -- $x
7838 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007839 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007840 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007841static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007842{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007843 int n;
7844 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007845 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007846
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007847 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007848 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007849 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007850 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007851 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007852 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007853
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007854 do {
7855 if (!strcmp(arg, "--")) {
7856 ++argv;
7857 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007858 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00007859 if (arg[0] != '+' && arg[0] != '-')
7860 break;
7861 for (n = 1; arg[n]; ++n)
7862 if (set_mode(arg[0], arg[n]))
7863 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007864 } while ((arg = *++argv) != NULL);
7865 /* Now argv[0] is 1st argument */
7866
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007867 if (arg == NULL)
7868 return EXIT_SUCCESS;
7869 set_argv:
7870
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007871 /* NB: G.global_argv[0] ($0) is never freed/changed */
7872 g_argv = G.global_argv;
7873 if (G.global_args_malloced) {
7874 pp = g_argv;
7875 while (*++pp)
7876 free(*pp);
7877 g_argv[1] = NULL;
7878 } else {
7879 G.global_args_malloced = 1;
7880 pp = xzalloc(sizeof(pp[0]) * 2);
7881 pp[0] = g_argv[0]; /* retain $0 */
7882 g_argv = pp;
7883 }
7884 /* This realloc's G.global_argv */
7885 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7886
7887 n = 1;
7888 while (*++pp)
7889 n++;
7890 G.global_argc = n;
7891
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007892 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007893
7894 /* Nothing known, so abort */
7895 error:
7896 bb_error_msg("set: %s: invalid option", arg);
7897 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007898}
7899
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007900static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007901{
7902 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007903 argv = skip_dash_dash(argv);
7904 if (argv[0]) {
7905 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007906 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007907 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007908 if (G.global_args_malloced) {
7909 int m = 1;
7910 while (m <= n)
7911 free(G.global_argv[m++]);
7912 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007913 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007914 memmove(&G.global_argv[1], &G.global_argv[n+1],
7915 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007916 return EXIT_SUCCESS;
7917 }
7918 return EXIT_FAILURE;
7919}
7920
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007921static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007922{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02007923 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007924 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007925 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007926#if ENABLE_HUSH_FUNCTIONS
7927 smallint sv_flg;
7928#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007929
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007930 argv = skip_dash_dash(argv);
7931 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02007932 if (!filename) {
7933 /* bash says: "bash: .: filename argument required" */
7934 return 2; /* bash compat */
7935 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007936 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02007937 if (!strchr(filename, '/')) {
7938 arg_path = find_in_path(filename);
7939 if (arg_path)
7940 filename = arg_path;
7941 }
7942 input = fopen_or_warn(filename, "r");
7943 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007944 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007945 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007946 return EXIT_FAILURE;
7947 }
7948 close_on_exec_on(fileno(input));
7949
Mike Frysinger885b6f22009-04-18 21:04:25 +00007950#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007951 sv_flg = G.flag_return_in_progress;
7952 /* "we are inside sourced file, ok to use return" */
7953 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007954#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007955 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007956
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007957 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007958 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007959
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007960 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00007961#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007962 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007963#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007964
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007965 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007966}
7967
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007968static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007969{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007970 int rc;
7971 mode_t mask;
7972
7973 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007974 argv = skip_dash_dash(argv);
7975 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007976 mode_t old_mask = mask;
7977
7978 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007979 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007980 mask ^= 0777;
7981 if (rc == 0) {
7982 mask = old_mask;
7983 /* bash messages:
7984 * bash: umask: 'q': invalid symbolic mode operator
7985 * bash: umask: 999: octal number out of range
7986 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02007987 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007988 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007989 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007990 rc = 1;
7991 /* Mimic bash */
7992 printf("%04o\n", (unsigned) mask);
7993 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007994 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007995 umask(mask);
7996
7997 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007998}
7999
Mike Frysingerd690f682009-03-30 06:50:54 +00008000/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008001static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008002{
Mike Frysingerd690f682009-03-30 06:50:54 +00008003 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008004 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008005
Denis Vlasenko28e67962009-04-26 23:22:40 +00008006 /* "!": do not abort on errors */
8007 /* "+": stop at 1st non-option */
8008 opts = getopt32(argv, "!+vf");
8009 if (opts == (unsigned)-1)
8010 return EXIT_FAILURE;
8011 if (opts == 3) {
8012 bb_error_msg("unset: -v and -f are exclusive");
8013 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008014 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008015 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008016
8017 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008018 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008019 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008020 if (unset_local_var(*argv)) {
8021 /* unset <nonexistent_var> doesn't fail.
8022 * Error is when one tries to unset RO var.
8023 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008024 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008025 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008026 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008027#if ENABLE_HUSH_FUNCTIONS
8028 else {
8029 unset_func(*argv);
8030 }
8031#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008032 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008033 }
8034 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008035}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008036
Mike Frysinger56bdea12009-03-28 20:01:58 +00008037/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008038static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008039{
8040 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008041 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008042
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008043 argv = skip_dash_dash(argv);
8044 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008045 /* Don't care about wait results */
8046 /* Note 1: must wait until there are no more children */
8047 /* Note 2: must be interruptible */
8048 /* Examples:
8049 * $ sleep 3 & sleep 6 & wait
8050 * [1] 30934 sleep 3
8051 * [2] 30935 sleep 6
8052 * [1] Done sleep 3
8053 * [2] Done sleep 6
8054 * $ sleep 3 & sleep 6 & wait
8055 * [1] 30936 sleep 3
8056 * [2] 30937 sleep 6
8057 * [1] Done sleep 3
8058 * ^C <-- after ~4 sec from keyboard
8059 * $
8060 */
8061 sigaddset(&G.blocked_set, SIGCHLD);
8062 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8063 while (1) {
8064 checkjobs(NULL);
8065 if (errno == ECHILD)
8066 break;
8067 /* Wait for SIGCHLD or any other signal of interest */
8068 /* sigtimedwait with infinite timeout: */
8069 sig = sigwaitinfo(&G.blocked_set, NULL);
8070 if (sig > 0) {
8071 sig = check_and_run_traps(sig);
8072 if (sig && sig != SIGCHLD) { /* see note 2 */
8073 ret = 128 + sig;
8074 break;
8075 }
8076 }
8077 }
8078 sigdelset(&G.blocked_set, SIGCHLD);
8079 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8080 return ret;
8081 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008082
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008083 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008084 while (*argv) {
8085 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008086 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008087 /* mimic bash message */
8088 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008089 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008090 }
8091 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008092 if (WIFSIGNALED(status))
8093 ret = 128 + WTERMSIG(status);
8094 else if (WIFEXITED(status))
8095 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008096 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008097 ret = EXIT_FAILURE;
8098 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008099 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008100 ret = 127;
8101 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008102 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008103 }
8104
8105 return ret;
8106}
8107
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008108#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8109static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8110{
8111 if (argv[1]) {
8112 def = bb_strtou(argv[1], NULL, 10);
8113 if (errno || def < def_min || argv[2]) {
8114 bb_error_msg("%s: bad arguments", argv[0]);
8115 def = UINT_MAX;
8116 }
8117 }
8118 return def;
8119}
8120#endif
8121
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008122#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008123static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008124{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008125 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008126 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008127 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008128 return EXIT_SUCCESS; /* bash compat */
8129 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008130 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008131
8132 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8133 if (depth == UINT_MAX)
8134 G.flag_break_continue = BC_BREAK;
8135 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008136 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008137
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008138 return EXIT_SUCCESS;
8139}
8140
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008141static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008142{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008143 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8144 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008145}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008146#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008147
8148#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008149static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008150{
8151 int rc;
8152
8153 if (G.flag_return_in_progress != -1) {
8154 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8155 return EXIT_FAILURE; /* bash compat */
8156 }
8157
8158 G.flag_return_in_progress = 1;
8159
8160 /* bash:
8161 * out of range: wraps around at 256, does not error out
8162 * non-numeric param:
8163 * f() { false; return qwe; }; f; echo $?
8164 * bash: return: qwe: numeric argument required <== we do this
8165 * 255 <== we also do this
8166 */
8167 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8168 return rc;
8169}
8170#endif