blob: d75b0da7e467e8f7bd204850ffa41081e4a41ba6 [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
Eric Andersen25f27032001-04-26 23:22:31 +000042 * <(list) and >(list) Process Substitution
Mike Frysinger25a6ca02009-03-28 13:59:26 +000043 * Tilde Expansion
Mike Frysinger25a6ca02009-03-28 13:59:26 +000044 *
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020045 * Bash stuff (optionally enabled):
Mike Frysinger25a6ca02009-03-28 13:59:26 +000046 * &> and >& redirection of stdout+stderr
Denys Vlasenko08218012009-06-03 14:43:56 +020047 * Brace Expansion
Mike Frysinger25a6ca02009-03-28 13:59:26 +000048 * reserved words: [[ ]] function select
Mike Frysinger6379bb42009-03-28 18:55:03 +000049 * substrings ${var:1:5}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020050 * let EXPR [EXPR...]
51 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
52 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
53 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
54 * ((EXPR))
55 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
56 * This is exactly equivalent to let "expression".
Mike Frysinger25a6ca02009-03-28 13:59:26 +000057 *
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000058 * TODOs:
59 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020060 * builtins: ulimit
Denys Vlasenko6db47842009-09-05 20:15:17 +020061 * special variables (done: PWD)
Eric Andersen25f27032001-04-26 23:22:31 +000062 * follow IFS rules more precisely, including update semantics
Denys Vlasenko08218012009-06-03 14:43:56 +020063 * export builtin should be special, its arguments are assignments
64 * and therefore expansion of them should be "one-word" expansion:
65 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
66 * compare with:
67 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
68 * ls: cannot access i=a: No such file or directory
69 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020070 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020071 * Note2: bash 3.2.33(1) does this only if export word itself
72 * is not quoted:
73 * $ export i=`echo 'aaa bbb'`; echo "$i"
74 * aaa bbb
75 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
76 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000077 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000078 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000079 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020080#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denys Vlasenko27726cb2009-09-12 14:48:33 +020081#include <malloc.h> /* for malloc_trim */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000082#include <glob.h>
83/* #include <dmalloc.h> */
84#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000085# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000086#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000087#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000088#include "match.h"
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000089#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020090# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000091#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000092
Denis Vlasenko1943aec2009-04-09 14:15:57 +000093
Denys Vlasenko8d7be232009-05-25 16:38:32 +020094/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000095#define LEAK_HUNTING 0
96#define BUILD_AS_NOMMU 0
97/* Enable/disable sanity checks. Ok to enable in production,
98 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
99 * Keeping 1 for now even in released versions.
100 */
101#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200102/* Slightly bigger (+200 bytes), but faster hush.
103 * So far it only enables a trick with counting SIGCHLDs and forks,
104 * which allows us to do fewer waitpid's.
105 * (we can detect a case where neither forks were done nor SIGCHLDs happened
106 * and therefore waitpid will return the same result as last time)
107 */
108#define ENABLE_HUSH_FAST 0
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000109
110
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000111#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000112# undef BB_MMU
113# undef USE_FOR_NOMMU
114# undef USE_FOR_MMU
115# define BB_MMU 0
116# define USE_FOR_NOMMU(...) __VA_ARGS__
117# define USE_FOR_MMU(...)
118#endif
119
Denis Vlasenko61befda2008-11-25 01:36:03 +0000120#if defined SINGLE_APPLET_MAIN
121/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000122# undef CONFIG_FEATURE_SH_STANDALONE
123# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000124# undef IF_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000125# define IF_FEATURE_SH_STANDALONE(...)
126# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denys Vlasenko673e9452009-05-27 14:39:35 +0200127# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko61befda2008-11-25 01:36:03 +0000128#endif
129
Denis Vlasenko05743d72008-02-10 12:10:08 +0000130#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000131# undef ENABLE_FEATURE_EDITING
132# define ENABLE_FEATURE_EDITING 0
133# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
134# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000135#endif
136
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000137/* Do we support ANY keywords? */
138#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000139# define HAS_KEYWORDS 1
140# define IF_HAS_KEYWORDS(...) __VA_ARGS__
141# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000142#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000143# define HAS_KEYWORDS 0
144# define IF_HAS_KEYWORDS(...)
145# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000146#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000147
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000148/* If you comment out one of these below, it will be #defined later
149 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000150#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000151/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000152#define debug_printf_parse(...) do {} while (0)
153#define debug_print_tree(a, b) do {} while (0)
154#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000155#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000156#define debug_printf_jobs(...) do {} while (0)
157#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000158#define debug_printf_glob(...) do {} while (0)
159#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000160#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000161#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000162
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000163#define ERR_PTR ((void*)(long)1)
164
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000165#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000166
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000167#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000168
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200169struct variable;
170
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000171static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
172
173/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000174 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000175 */
176#if !BB_MMU
177typedef struct nommu_save_t {
178 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200179 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000180 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000181 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000182} nommu_save_t;
183#endif
184
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000185typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000186 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000187#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000188 RES_IF ,
189 RES_THEN ,
190 RES_ELIF ,
191 RES_ELSE ,
192 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000193#endif
194#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000195 RES_FOR ,
196 RES_WHILE ,
197 RES_UNTIL ,
198 RES_DO ,
199 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000200#endif
201#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000202 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000203#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000204#if ENABLE_HUSH_CASE
205 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200206 /* three pseudo-keywords support contrived "case" syntax: */
207 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
208 RES_MATCH , /* "word)" */
209 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000210 RES_ESAC ,
211#endif
212 RES_XXXX ,
213 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000214} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000215
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000216typedef struct o_string {
217 char *data;
218 int length; /* position where data is appended */
219 int maxlen;
220 /* Protect newly added chars against globbing
221 * (by prepending \ to *, ?, [, \) */
222 smallint o_escape;
223 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000224 /* At least some part of the string was inside '' or "",
225 * possibly empty one: word"", wo''rd etc. */
226 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000227 smallint has_empty_slot;
228 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
229} o_string;
230enum {
231 MAYBE_ASSIGNMENT = 0,
232 DEFINITELY_ASSIGNMENT = 1,
233 NOT_ASSIGNMENT = 2,
234 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
235};
236/* Used for initialization: o_string foo = NULL_O_STRING; */
237#define NULL_O_STRING { NULL }
238
239/* I can almost use ordinary FILE*. Is open_memstream() universally
240 * available? Where is it documented? */
241typedef struct in_str {
242 const char *p;
243 /* eof_flag=1: last char in ->p is really an EOF */
244 char eof_flag; /* meaningless if ->p == NULL */
245 char peek_buf[2];
246#if ENABLE_HUSH_INTERACTIVE
247 smallint promptme;
248 smallint promptmode; /* 0: PS1, 1: PS2 */
249#endif
250 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200251 int (*get) (struct in_str *) FAST_FUNC;
252 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000253} in_str;
254#define i_getch(input) ((input)->get(input))
255#define i_peek(input) ((input)->peek(input))
256
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200257/* The descrip member of this structure is only used to make
258 * debugging output pretty */
259static const struct {
260 int mode;
261 signed char default_fd;
262 char descrip[3];
263} redir_table[] = {
264 { O_RDONLY, 0, "<" },
265 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
266 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
267 { O_CREAT|O_RDWR, 1, "<>" },
268 { O_RDONLY, 0, "<<" },
269/* Should not be needed. Bogus default_fd helps in debugging */
270/* { O_RDONLY, 77, "<<" }, */
271};
272
Eric Andersen25f27032001-04-26 23:22:31 +0000273struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000274 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000275 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000276 int rd_fd; /* fd to redirect */
277 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
278 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000279 smallint rd_type; /* (enum redir_type) */
280 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000281 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200282 * bit 0: do we need to trim leading tabs?
283 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000284 */
Eric Andersen25f27032001-04-26 23:22:31 +0000285};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000286typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200287 REDIRECT_INPUT = 0,
288 REDIRECT_OVERWRITE = 1,
289 REDIRECT_APPEND = 2,
290 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000291 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200292 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000293
294 REDIRFD_CLOSE = -3,
295 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000296 REDIRFD_TO_FILE = -1,
297 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000298
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000299 HEREDOC_SKIPTABS = 1,
300 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000301} redir_type;
302
Eric Andersen25f27032001-04-26 23:22:31 +0000303
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000304struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000305 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000306 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000307 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200308 smallint cmd_type; /* CMD_xxx */
309#define CMD_NORMAL 0
310#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200311
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200312/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200313#if ENABLE_HUSH_BASH_COMPAT
314# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000315#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200316
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200317/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200318//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200319// It is hard to implement correctly, it adds significant amounts of tricky code,
320// and all this is only useful for really obscure export statements
321// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
322// guards the code which implements it, but I have doubts it works
323// in all cases (especially with mixed globbed/non-globbed arguments)
324
325#if ENABLE_HUSH_FUNCTIONS
326# define CMD_FUNCDEF 3
327#endif
328
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200329 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
330 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000331#if !BB_MMU
332 char *group_as_string;
333#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000334#if ENABLE_HUSH_FUNCTIONS
335 struct function *child_func;
336/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200337 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000338 * When we execute "f1() {a;}" cmd, we create new function and clear
339 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200340 * When we execute "f1() {b;}", we notice that f1 exists,
341 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000342 * we put those fields back into cmd->xxx
343 * (struct function has ->parent_cmd ptr to facilitate that).
344 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
345 * Without this trick, loop would execute a;b;b;b;...
346 * instead of correct sequence a;b;a;b;...
347 * When command is freed, it severs the link
348 * (sets ->child_func->parent_cmd to NULL).
349 */
350#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000351 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000352/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
353 * and on execution these are substituted with their values.
354 * Substitution can make _several_ words out of one argv[n]!
355 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000356 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000357 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000358 struct redir_struct *redirects; /* I/O redirections */
359};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000360/* Is there anything in this command at all? */
361#define IS_NULL_CMD(cmd) \
362 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
363
Eric Andersen25f27032001-04-26 23:22:31 +0000364
365struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000366 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000367 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000368 int alive_cmds; /* number of commands running (not exited) */
369 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000370#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000371 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000372 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000373 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000374#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000375 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000376 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000377 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
378 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000379};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000380typedef enum pipe_style {
381 PIPE_SEQ = 1,
382 PIPE_AND = 2,
383 PIPE_OR = 3,
384 PIPE_BG = 4,
385} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000386/* Is there anything in this pipe at all? */
387#define IS_NULL_PIPE(pi) \
388 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000389
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000390/* This holds pointers to the various results of parsing */
391struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000392 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000393 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000394 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000395 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000396 /* last command in pipe (being constructed right now) */
397 struct command *command;
398 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000399 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000400#if !BB_MMU
401 o_string as_string;
402#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000403#if HAS_KEYWORDS
404 smallint ctx_res_w;
405 smallint ctx_inverted; /* "! cmd | cmd" */
406#if ENABLE_HUSH_CASE
407 smallint ctx_dsemicolon; /* ";;" seen */
408#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000409 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
410 int old_flag;
411 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000412 * example: "if pipe1; pipe2; then pipe3; fi"
413 * when we see "if" or "then", we malloc and copy current context,
414 * and make ->stack point to it. then we parse pipeN.
415 * when closing "then" / fi" / whatever is found,
416 * we move list_head into ->stack->command->group,
417 * copy ->stack into current context, and delete ->stack.
418 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000419 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000420 struct parse_context *stack;
421#endif
422};
423
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000424/* On program start, environ points to initial environment.
425 * putenv adds new pointers into it, unsetenv removes them.
426 * Neither of these (de)allocates the strings.
427 * setenv allocates new strings in malloc space and does putenv,
428 * and thus setenv is unusable (leaky) for shell's purposes */
429#define setenv(...) setenv_is_leaky_dont_use()
430struct variable {
431 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000432 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200433#if ENABLE_HUSH_LOCAL
434 unsigned func_nest_level;
435#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000436 int max_len; /* if > 0, name is part of initial env; else name is malloced */
437 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000438 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000439};
440
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000441enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000442 BC_BREAK = 1,
443 BC_CONTINUE = 2,
444};
445
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000446#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000447struct function {
448 struct function *next;
449 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000450 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000451 struct pipe *body;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000452#if !BB_MMU
453 char *body_as_string;
454#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000455};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000456#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000457
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000458
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000459/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000460/* Sorted roughly by size (smaller offsets == smaller code) */
461struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000462 /* interactive_fd != 0 means we are an interactive shell.
463 * If we are, then saved_tty_pgrp can also be != 0, meaning
464 * that controlling tty is available. With saved_tty_pgrp == 0,
465 * job control still works, but terminal signals
466 * (^C, ^Z, ^Y, ^\) won't work at all, and background
467 * process groups can only be created with "cmd &".
468 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
469 * to give tty to the foreground process group,
470 * and will take it back when the group is stopped (^Z)
471 * or killed (^C).
472 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000473#if ENABLE_HUSH_INTERACTIVE
474 /* 'interactive_fd' is a fd# open to ctty, if we have one
475 * _AND_ if we decided to act interactively */
476 int interactive_fd;
477 const char *PS1;
478 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000479# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000480#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000481# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000482#endif
483#if ENABLE_FEATURE_EDITING
484 line_input_t *line_input_state;
485#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000486 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000487 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000488#if ENABLE_HUSH_JOB
489 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000490 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000491 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000492 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400493# define G_saved_tty_pgrp (G.saved_tty_pgrp)
494#else
495# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000496#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000497 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000498#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000499 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000500#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000501#if ENABLE_HUSH_FUNCTIONS
502 /* 0: outside of a function (or sourced file)
503 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000504 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000505 */
506 smallint flag_return_in_progress;
507#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000508 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000509 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000510 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000511 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000512 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000513 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000514 /* how many non-NULL argv's we have. NB: $# + 1 */
515 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000516 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000517#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000518 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000519#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000520#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000521 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000522 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000523#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000524 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000525 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000526 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000527 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000528#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000529 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200530# if ENABLE_HUSH_LOCAL
531 struct variable **shadowed_vars_pp;
532 unsigned func_nest_level;
533# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000534#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000535 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200536#if ENABLE_HUSH_FAST
537 unsigned count_SIGCHLD;
538 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200539 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200540#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000541 /* which signals have non-DFL handler (even with no traps set)? */
542 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000543 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000544 sigset_t blocked_set;
545 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000546#if HUSH_DEBUG
547 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000548 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000549#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000550 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000551};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000552#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000553/* Not #defining name to G.name - this quickly gets unwieldy
554 * (too many defines). Also, I actually prefer to see when a variable
555 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000556#define INIT_G() do { \
557 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
558} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000559
560
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000561/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200562static int builtin_cd(char **argv) FAST_FUNC;
563static int builtin_echo(char **argv) FAST_FUNC;
564static int builtin_eval(char **argv) FAST_FUNC;
565static int builtin_exec(char **argv) FAST_FUNC;
566static int builtin_exit(char **argv) FAST_FUNC;
567static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000568#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200569static int builtin_fg_bg(char **argv) FAST_FUNC;
570static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000571#endif
572#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200573static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000574#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200575#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200576static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200577#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000578#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200579static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000580#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200581static int builtin_pwd(char **argv) FAST_FUNC;
582static int builtin_read(char **argv) FAST_FUNC;
583static int builtin_set(char **argv) FAST_FUNC;
584static int builtin_shift(char **argv) FAST_FUNC;
585static int builtin_source(char **argv) FAST_FUNC;
586static int builtin_test(char **argv) FAST_FUNC;
587static int builtin_trap(char **argv) FAST_FUNC;
588static int builtin_type(char **argv) FAST_FUNC;
589static int builtin_true(char **argv) FAST_FUNC;
590static int builtin_umask(char **argv) FAST_FUNC;
591static int builtin_unset(char **argv) FAST_FUNC;
592static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000593#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200594static int builtin_break(char **argv) FAST_FUNC;
595static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000596#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000597#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200598static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000599#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000600
601/* Table of built-in functions. They can be forked or not, depending on
602 * context: within pipes, they fork. As simple commands, they do not.
603 * When used in non-forking context, they can change global variables
604 * in the parent shell process. If forked, of course they cannot.
605 * For example, 'unset foo | whatever' will parse and run, but foo will
606 * still be set at the end. */
607struct built_in_command {
608 const char *cmd;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200609 int (*function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000610#if ENABLE_HUSH_HELP
611 const char *descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200612# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000613#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200614# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000615#endif
616};
617
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200618static const struct built_in_command bltins1[] = {
619 BLTIN("." , builtin_source , "Run commands in a file"),
620 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000621#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200622 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000623#endif
624#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200625 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000626#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200627 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000628#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200629 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000630#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200631 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
632 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
633 BLTIN("exit" , builtin_exit , "Exit"),
634 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000635#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200636 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000637#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000638#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200639 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000640#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000641#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200642 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000643#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200644#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200645 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200646#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000647#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200648 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000649#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200650 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000651#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200652 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000653#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200654 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
655 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
656 BLTIN("trap" , builtin_trap , "Trap signals"),
657 BLTIN("type" , builtin_type , "Write a description of command type"),
658// BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
659 BLTIN("umask" , builtin_umask , "Set file creation mask"),
660 BLTIN("unset" , builtin_unset , "Unset variables"),
661 BLTIN("wait" , builtin_wait , "Wait for process"),
662};
663/* For now, echo and test are unconditionally enabled.
664 * Maybe make it configurable? */
665static const struct built_in_command bltins2[] = {
666 BLTIN("[" , builtin_test , NULL),
667 BLTIN("echo" , builtin_echo , NULL),
668 BLTIN("pwd" , builtin_pwd , NULL),
669 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000670};
671
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000672
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000673/* Debug printouts.
674 */
675#if HUSH_DEBUG
676/* prevent disasters with G.debug_indent < 0 */
677# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
678# define debug_enter() (G.debug_indent++)
679# define debug_leave() (G.debug_indent--)
680#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200681# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000682# define debug_enter() ((void)0)
683# define debug_leave() ((void)0)
684#endif
685
686#ifndef debug_printf
687# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
688#endif
689
690#ifndef debug_printf_parse
691# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
692#endif
693
694#ifndef debug_printf_exec
695#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
696#endif
697
698#ifndef debug_printf_env
699# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
700#endif
701
702#ifndef debug_printf_jobs
703# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
704# define DEBUG_JOBS 1
705#else
706# define DEBUG_JOBS 0
707#endif
708
709#ifndef debug_printf_expand
710# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
711# define DEBUG_EXPAND 1
712#else
713# define DEBUG_EXPAND 0
714#endif
715
716#ifndef debug_printf_glob
717# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
718# define DEBUG_GLOB 1
719#else
720# define DEBUG_GLOB 0
721#endif
722
723#ifndef debug_printf_list
724# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
725#endif
726
727#ifndef debug_printf_subst
728# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
729#endif
730
731#ifndef debug_printf_clean
732# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
733# define DEBUG_CLEAN 1
734#else
735# define DEBUG_CLEAN 0
736#endif
737
738#if DEBUG_EXPAND
739static void debug_print_strings(const char *prefix, char **vv)
740{
741 indent();
742 fprintf(stderr, "%s:\n", prefix);
743 while (*vv)
744 fprintf(stderr, " '%s'\n", *vv++);
745}
746#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200747# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000748#endif
749
750
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000751/* Leak hunting. Use hush_leaktool.sh for post-processing.
752 */
753#if LEAK_HUNTING
754static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000755{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000756 void *ptr = xmalloc((size + 0xff) & ~0xff);
757 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
758 return ptr;
759}
760static void *xxrealloc(int lineno, void *ptr, size_t size)
761{
762 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
763 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
764 return ptr;
765}
766static char *xxstrdup(int lineno, const char *str)
767{
768 char *ptr = xstrdup(str);
769 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
770 return ptr;
771}
772static void xxfree(void *ptr)
773{
774 fdprintf(2, "free %p\n", ptr);
775 free(ptr);
776}
777#define xmalloc(s) xxmalloc(__LINE__, s)
778#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
779#define xstrdup(s) xxstrdup(__LINE__, s)
780#define free(p) xxfree(p)
781#endif
782
783
784/* Syntax and runtime errors. They always abort scripts.
785 * In interactive use they usually discard unparsed and/or unexecuted commands
786 * and return to the prompt.
787 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
788 */
789#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200790# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000791# define syntax_error(lineno, msg) syntax_error(msg)
792# define syntax_error_at(lineno, msg) syntax_error_at(msg)
793# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
794# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
795# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000796#endif
797
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000798static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000799{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000800 va_list p;
801
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000802#if HUSH_DEBUG >= 2
803 bb_error_msg("hush.c:%u", lineno);
804#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000805 va_start(p, fmt);
806 bb_verror_msg(fmt, p, NULL);
807 va_end(p);
808 if (!G_interactive_fd)
809 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000810}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000811
812static void syntax_error(unsigned lineno, const char *msg)
813{
814 if (msg)
815 die_if_script(lineno, "syntax error: %s", msg);
816 else
817 die_if_script(lineno, "syntax error", NULL);
818}
819
820static void syntax_error_at(unsigned lineno, const char *msg)
821{
822 die_if_script(lineno, "syntax error at '%s'", msg);
823}
824
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400825static void syntax_error_unterm_str(unsigned lineno, const char *s)
826{
827 die_if_script(lineno, "syntax error: unterminated %s", s);
828}
829
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000830/* It so happens that all such cases are totally fatal
831 * even if shell is interactive: EOF while looking for closing
832 * delimiter. There is nowhere to read stuff from after that,
833 * it's EOF! The only choice is to terminate.
834 */
835static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000836static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000837{
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400838 char msg[2] = { ch, '\0' };
839 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000840 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000841}
842
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200843static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000844{
845 char msg[2];
846 msg[0] = ch;
847 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200848 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000849}
850
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000851#if HUSH_DEBUG < 2
852# undef die_if_script
853# undef syntax_error
854# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000855# undef syntax_error_unterm_ch
856# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000857# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000858#else
Denys Vlasenko606291b2009-09-23 23:15:43 +0200859# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000860# define syntax_error(msg) syntax_error(__LINE__, msg)
861# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
862# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
863# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
864# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000865#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000866
Denis Vlasenko552433b2009-04-04 19:29:21 +0000867
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000868#if ENABLE_HUSH_INTERACTIVE
869static void cmdedit_update_prompt(void);
870#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200871# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000872#endif
873
874
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000875/* Utility functions
876 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000877static int glob_needed(const char *s)
878{
879 while (*s) {
880 if (*s == '\\')
881 s++;
882 if (*s == '*' || *s == '[' || *s == '?')
883 return 1;
884 s++;
885 }
886 return 0;
887}
888
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000889static int is_well_formed_var_name(const char *s, char terminator)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000890{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000891 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000892 return 0;
893 s++;
894 while (isalnum(*s) || *s == '_')
895 s++;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000896 return *s == terminator;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000897}
898
Denis Vlasenko55789c62008-06-18 16:30:42 +0000899/* Replace each \x with x in place, return ptr past NUL. */
900static char *unbackslash(char *src)
901{
Denys Vlasenko71885402009-09-24 01:44:13 +0200902 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +0000903 while (1) {
904 if (*src == '\\')
905 src++;
906 if ((*dst++ = *src++) == '\0')
907 break;
908 }
909 return dst;
910}
911
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000912static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000913{
914 int i;
915 unsigned count1;
916 unsigned count2;
917 char **v;
918
919 v = strings;
920 count1 = 0;
921 if (v) {
922 while (*v) {
923 count1++;
924 v++;
925 }
926 }
927 count2 = 0;
928 v = add;
929 while (*v) {
930 count2++;
931 v++;
932 }
933 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
934 v[count1 + count2] = NULL;
935 i = count2;
936 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000937 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000938 return v;
939}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000940#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000941static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
942{
943 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
944 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
945 return ptr;
946}
947#define add_strings_to_strings(strings, add, need_to_dup) \
948 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
949#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000950
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200951/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000952static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000953{
954 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000955 v[0] = add;
956 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000957 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000958}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000959#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000960static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
961{
962 char **ptr = add_string_to_strings(strings, add);
963 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
964 return ptr;
965}
966#define add_string_to_strings(strings, add) \
967 xx_add_string_to_strings(__LINE__, strings, add)
968#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000969
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200970static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000971{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000972 char **v;
973
974 if (!strings)
975 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000976 v = strings;
977 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200978 free(*v);
979 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000980 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000981 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000982}
983
Denis Vlasenko76d50412008-06-10 16:19:39 +0000984
Denis Vlasenko270b1c32009-04-17 18:54:50 +0000985/* Helpers for setting new $n and restoring them back
986 */
987typedef struct save_arg_t {
988 char *sv_argv0;
989 char **sv_g_argv;
990 int sv_g_argc;
991 smallint sv_g_malloced;
992} save_arg_t;
993
994static void save_and_replace_G_args(save_arg_t *sv, char **argv)
995{
996 int n;
997
998 sv->sv_argv0 = argv[0];
999 sv->sv_g_argv = G.global_argv;
1000 sv->sv_g_argc = G.global_argc;
1001 sv->sv_g_malloced = G.global_args_malloced;
1002
1003 argv[0] = G.global_argv[0]; /* retain $0 */
1004 G.global_argv = argv;
1005 G.global_args_malloced = 0;
1006
1007 n = 1;
1008 while (*++argv)
1009 n++;
1010 G.global_argc = n;
1011}
1012
1013static void restore_G_args(save_arg_t *sv, char **argv)
1014{
1015 char **pp;
1016
1017 if (G.global_args_malloced) {
1018 /* someone ran "set -- arg1 arg2 ...", undo */
1019 pp = G.global_argv;
1020 while (*++pp) /* note: does not free $0 */
1021 free(*pp);
1022 free(G.global_argv);
1023 }
1024 argv[0] = sv->sv_argv0;
1025 G.global_argv = sv->sv_g_argv;
1026 G.global_argc = sv->sv_g_argc;
1027 G.global_args_malloced = sv->sv_g_malloced;
1028}
1029
1030
Denis Vlasenkod5762932009-03-31 11:22:57 +00001031/* Basic theory of signal handling in shell
1032 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001033 * This does not describe what hush does, rather, it is current understanding
1034 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001035 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1036 *
1037 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1038 * is finished or backgrounded. It is the same in interactive and
1039 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001040 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001041 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001042 * backgrounds (i.e. stops) or kills all members of currently running
1043 * pipe.
1044 *
1045 * Wait builtin in interruptible by signals for which user trap is set
1046 * or by SIGINT in interactive shell.
1047 *
1048 * Trap handlers will execute even within trap handlers. (right?)
1049 *
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001050 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001051 *
1052 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001053 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001054 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001055 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001056 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001057 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001058 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001059 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001060 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001061 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001062 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001063 *
1064 * SIGQUIT: ignore
1065 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001066 * SIGHUP (interactive):
1067 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001068 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001069 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1070 * that all pipe members are stopped. Try this in bash:
1071 * while :; do :; done - ^Z does not background it
1072 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001073 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001074 * of the command line, show prompt. NB: ^C does not send SIGINT
1075 * to interactive shell while shell is waiting for a pipe,
1076 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001077 * Example 1: this waits 5 sec, but does not execute ls:
1078 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1079 * Example 2: this does not wait and does not execute ls:
1080 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1081 * Example 3: this does not wait 5 sec, but executes ls:
1082 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001083 *
1084 * (What happens to signals which are IGN on shell start?)
1085 * (What happens with signal mask on shell start?)
1086 *
1087 * Implementation in hush
1088 * ======================
1089 * We use in-kernel pending signal mask to determine which signals were sent.
1090 * We block all signals which we don't want to take action immediately,
1091 * i.e. we block all signals which need to have special handling as described
1092 * above, and all signals which have traps set.
1093 * After each pipe execution, we extract any pending signals via sigtimedwait()
1094 * and act on them.
1095 *
1096 * unsigned non_DFL_mask: a mask of such "special" signals
1097 * sigset_t blocked_set: current blocked signal set
1098 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001099 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001100 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001101 * "trap 'cmd' SIGxxx":
1102 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001103 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001104 * unblock signals with special interactive handling
1105 * (child shell is not interactive),
1106 * unset all traps (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001107 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001108 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001109 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001110 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001111 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001112 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001113 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001114 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001115 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001116 * Standard says "When a subshell is entered, traps that are not being ignored
1117 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenko67f71862009-09-25 14:21:06 +02001118 * are set to "" (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001119 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001120enum {
1121 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001122 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001123 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001124 | (1 << SIGHUP)
1125 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001126 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001127#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001128 | (1 << SIGTTIN)
1129 | (1 << SIGTTOU)
1130 | (1 << SIGTSTP)
1131#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001132};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001133
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001134#if ENABLE_HUSH_FAST
1135static void SIGCHLD_handler(int sig UNUSED_PARAM)
1136{
1137 G.count_SIGCHLD++;
1138//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1139}
1140#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001141
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001142#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001143
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001144/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1145#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001146/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001147#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1148
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001149/* Restores tty foreground process group, and exits.
1150 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001151 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001152 * or called directly with -EXITCODE.
1153 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001154static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001155static void sigexit(int sig)
1156{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001157 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001158 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001159
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001160 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001161 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001162 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1163 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001164
1165 /* Not a signal, just exit */
1166 if (sig <= 0)
1167 _exit(- sig);
1168
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001169 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001170}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001171#else
1172
1173#define disable_restore_tty_pgrp_on_exit() ((void)0)
1174#define enable_restore_tty_pgrp_on_exit() ((void)0)
1175
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001176#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001177
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001178/* Restores tty foreground process group, and exits. */
1179static void hush_exit(int exitcode) NORETURN;
1180static void hush_exit(int exitcode)
1181{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001182 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1183 /* Prevent recursion:
1184 * trap "echo Hi; exit" EXIT; exit
1185 */
1186 char *argv[] = { NULL, G.traps[0], NULL };
1187 G.traps[0] = NULL;
1188 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001189 builtin_eval(argv);
1190 free(argv[1]);
1191 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001192
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001193#if ENABLE_HUSH_JOB
1194 fflush(NULL); /* flush all streams */
1195 sigexit(- (exitcode & 0xff));
1196#else
1197 exit(exitcode);
1198#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001199}
1200
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001201static int check_and_run_traps(int sig)
1202{
1203 static const struct timespec zero_timespec = { 0, 0 };
1204 smalluint save_rcode;
1205 int last_sig = 0;
1206
1207 if (sig)
1208 goto jump_in;
1209 while (1) {
1210 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1211 if (sig <= 0)
1212 break;
1213 jump_in:
1214 last_sig = sig;
1215 if (G.traps && G.traps[sig]) {
1216 if (G.traps[sig][0]) {
1217 /* We have user-defined handler */
1218 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1219 save_rcode = G.last_exitcode;
1220 builtin_eval(argv);
1221 free(argv[1]);
1222 G.last_exitcode = save_rcode;
1223 } /* else: "" trap, ignoring signal */
1224 continue;
1225 }
1226 /* not a trap: special action */
1227 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001228#if ENABLE_HUSH_FAST
1229 case SIGCHLD:
1230 G.count_SIGCHLD++;
1231//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1232 break;
1233#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001234 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001235 /* Builtin was ^C'ed, make it look prettier: */
1236 bb_putchar('\n');
1237 G.flag_SIGINT = 1;
1238 break;
1239#if ENABLE_HUSH_JOB
1240 case SIGHUP: {
1241 struct pipe *job;
1242 /* bash is observed to signal whole process groups,
1243 * not individual processes */
1244 for (job = G.job_list; job; job = job->next) {
1245 if (job->pgrp <= 0)
1246 continue;
1247 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1248 if (kill(- job->pgrp, SIGHUP) == 0)
1249 kill(- job->pgrp, SIGCONT);
1250 }
1251 sigexit(SIGHUP);
1252 }
1253#endif
1254 default: /* ignored: */
1255 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1256 break;
1257 }
1258 }
1259 return last_sig;
1260}
1261
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001262
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001263static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001264{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001265 if (force || G.cwd == NULL) {
1266 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1267 * we must not try to free(bb_msg_unknown) */
1268 if (G.cwd == bb_msg_unknown)
1269 G.cwd = NULL;
1270 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1271 if (!G.cwd)
1272 G.cwd = bb_msg_unknown;
1273 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001274 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001275}
1276
Denis Vlasenko83506862007-11-23 13:11:42 +00001277
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001278/*
1279 * Shell and environment variable support
1280 */
1281static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001282{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001283 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001284 struct variable *cur;
1285 int len;
1286
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001287 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001288 pp = &G.top_var;
1289 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001290 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001291 return pp;
1292 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001293 }
1294 return NULL;
1295}
1296
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001297static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001298{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001299 struct variable **pp = get_ptr_to_local_var(name);
1300 if (pp)
1301 return *pp;
1302 return NULL;
1303}
1304
1305static const char *get_local_var_value(const char *name)
1306{
1307 struct variable **pp = get_ptr_to_local_var(name);
1308 if (pp)
1309 return strchr((*pp)->varstr, '=') + 1;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001310 return NULL;
1311}
1312
1313/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001314 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001315 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001316 * 0: do not change export flag
1317 * (if creating new variable, flag will be 0)
1318 * 1: set export flag and putenv the variable
1319 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001320 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001321 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001322#if !BB_MMU && ENABLE_HUSH_LOCAL
1323/* all params are used */
1324#elif BB_MMU && ENABLE_HUSH_LOCAL
1325#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1326 set_local_var(str, flg_export, local_lvl)
1327#elif BB_MMU && !ENABLE_HUSH_LOCAL
1328#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001329 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001330#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1331#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1332 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001333#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001334static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001335{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001336 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001337 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001338 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001339 int name_len;
1340
Denis Vlasenko950bd722009-04-21 11:23:56 +00001341 eq_sign = strchr(str, '=');
1342 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001343 free(str);
1344 return -1;
1345 }
1346
Denis Vlasenko950bd722009-04-21 11:23:56 +00001347 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001348 var_pp = &G.top_var;
1349 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001350 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001351 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001352 continue;
1353 }
1354 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001355 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001356#if !BB_MMU
1357 if (!flg_read_only)
1358#endif
1359 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001360 free(str);
1361 return -1;
1362 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001363 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001364 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1365 *eq_sign = '\0';
1366 unsetenv(str);
1367 *eq_sign = '=';
1368 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001369#if ENABLE_HUSH_LOCAL
1370 if (cur->func_nest_level < local_lvl) {
1371 /* New variable is declared as local,
1372 * and existing one is global, or local
1373 * from enclosing function.
1374 * Remove and save old one: */
1375 *var_pp = cur->next;
1376 cur->next = *G.shadowed_vars_pp;
1377 *G.shadowed_vars_pp = cur;
1378 /* bash 3.2.33(1) and exported vars:
1379 * # export z=z
1380 * # f() { local z=a; env | grep ^z; }
1381 * # f
1382 * z=a
1383 * # env | grep ^z
1384 * z=z
1385 */
1386 if (cur->flg_export)
1387 flg_export = 1;
1388 break;
1389 }
1390#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001391 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001392 free_and_exp:
1393 free(str);
1394 goto exp;
1395 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001396 if (cur->max_len != 0) {
1397 if (cur->max_len >= strlen(str)) {
1398 /* This one is from startup env, reuse space */
1399 strcpy(cur->varstr, str);
1400 goto free_and_exp;
1401 }
1402 } else {
1403 /* max_len == 0 signifies "malloced" var, which we can
1404 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001405 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001406 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001407 cur->max_len = 0;
1408 goto set_str_and_exp;
1409 }
1410
Denys Vlasenko295fef82009-06-03 12:47:26 +02001411 /* Not found - create new variable struct */
1412 cur = xzalloc(sizeof(*cur));
1413#if ENABLE_HUSH_LOCAL
1414 cur->func_nest_level = local_lvl;
1415#endif
1416 cur->next = *var_pp;
1417 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001418
1419 set_str_and_exp:
1420 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001421#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001422 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001423#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001424 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001425 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001426 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001427 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1428 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001429 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001430 if (flg_export == -1) {
1431 cur->flg_export = 0;
1432 /* unsetenv was already done */
1433 } else {
1434 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1435 return putenv(cur->varstr);
1436 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001437 }
1438 return 0;
1439}
1440
Denys Vlasenko6db47842009-09-05 20:15:17 +02001441/* Used at startup and after each cd */
1442static void set_pwd_var(int exp)
1443{
1444 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1445 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1446}
1447
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001448static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001449{
1450 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001451 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001452
1453 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001454 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001455 var_pp = &G.top_var;
1456 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001457 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1458 if (cur->flg_read_only) {
1459 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001460 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001461 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001462 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001463 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1464 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001465 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1466 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001467 if (!cur->max_len)
1468 free(cur->varstr);
1469 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001470 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001471 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001472 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001473 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001474 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001475}
1476
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001477static int unset_local_var(const char *name)
1478{
1479 return unset_local_var_len(name, strlen(name));
1480}
1481
1482static void unset_vars(char **strings)
1483{
1484 char **v;
1485
1486 if (!strings)
1487 return;
1488 v = strings;
1489 while (*v) {
1490 const char *eq = strchrnul(*v, '=');
1491 unset_local_var_len(*v, (int)(eq - *v));
1492 v++;
1493 }
1494 free(strings);
1495}
1496
Mike Frysinger98c52642009-04-02 10:02:37 +00001497#if ENABLE_SH_MATH_SUPPORT
1498#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1499#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1500static char *endofname(const char *name)
1501{
1502 char *p;
1503
1504 p = (char *) name;
1505 if (!is_name(*p))
1506 return p;
1507 while (*++p) {
1508 if (!is_in_name(*p))
1509 break;
1510 }
1511 return p;
1512}
1513
1514static void arith_set_local_var(const char *name, const char *val, int flags)
1515{
1516 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001517 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001518 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001519}
1520#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001521
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001522
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001523/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001524 * Helpers for "var1=val1 var2=val2 cmd" feature
1525 */
1526static void add_vars(struct variable *var)
1527{
1528 struct variable *next;
1529
1530 while (var) {
1531 next = var->next;
1532 var->next = G.top_var;
1533 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001534 if (var->flg_export) {
1535 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001536 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001537 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001538 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001539 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001540 var = next;
1541 }
1542}
1543
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001544static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001545{
1546 char **s;
1547 struct variable *old = NULL;
1548
1549 if (!strings)
1550 return old;
1551 s = strings;
1552 while (*s) {
1553 struct variable *var_p;
1554 struct variable **var_pp;
1555 char *eq;
1556
1557 eq = strchr(*s, '=');
1558 if (eq) {
1559 *eq = '\0';
1560 var_pp = get_ptr_to_local_var(*s);
1561 *eq = '=';
1562 if (var_pp) {
1563 /* Remove variable from global linked list */
1564 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001565 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001566 *var_pp = var_p->next;
1567 /* Add it to returned list */
1568 var_p->next = old;
1569 old = var_p;
1570 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001571 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001572 }
1573 s++;
1574 }
1575 return old;
1576}
1577
1578
1579/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001580 * in_str support
1581 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001582static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001583{
1584 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001585 if (ch != '\0')
1586 return ch;
1587 i->p--;
1588 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001589}
1590
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001591static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001592{
1593 return *i->p;
1594}
1595
1596#if ENABLE_HUSH_INTERACTIVE
1597
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001598static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001599{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001600 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001601 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001602 if (G.PS1 == NULL)
1603 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001604 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001605 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001606 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001607 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001608 if (G.PS2 == NULL)
1609 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001610}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001611
1612static const char* setup_prompt_string(int promptmode)
1613{
1614 const char *prompt_str;
1615 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001616 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1617 /* Set up the prompt */
1618 if (promptmode == 0) { /* PS1 */
1619 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001620 /* bash uses $PWD value, even if it is set by user.
1621 * It uses current dir only if PWD is unset.
1622 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001623 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001624 prompt_str = G.PS1;
1625 } else
1626 prompt_str = G.PS2;
1627 } else
1628 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001629 debug_printf("result '%s'\n", prompt_str);
1630 return prompt_str;
1631}
1632
1633static void get_user_input(struct in_str *i)
1634{
1635 int r;
1636 const char *prompt_str;
1637
1638 prompt_str = setup_prompt_string(i->promptmode);
1639#if ENABLE_FEATURE_EDITING
1640 /* Enable command line editing only while a command line
1641 * is actually being read */
1642 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001643 G.flag_SIGINT = 0;
1644 /* buglet: SIGINT will not make new prompt to appear _at once_,
1645 * only after <Enter>. (^C will work) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001646 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001647 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001648 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001649 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001650 i->eof_flag = (r < 0);
1651 if (i->eof_flag) { /* EOF/error detected */
1652 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1653 G.user_input_buf[1] = '\0';
1654 }
1655#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001656 do {
1657 G.flag_SIGINT = 0;
1658 fputs(prompt_str, stdout);
1659 fflush(stdout);
1660 G.user_input_buf[0] = r = fgetc(i->file);
1661 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001662//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001663 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001664 i->eof_flag = (r == EOF);
1665#endif
1666 i->p = G.user_input_buf;
1667}
1668
1669#endif /* INTERACTIVE */
1670
1671/* This is the magic location that prints prompts
1672 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001673static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001674{
1675 int ch;
1676
1677 /* If there is data waiting, eat it up */
1678 if (i->p && *i->p) {
1679#if ENABLE_HUSH_INTERACTIVE
1680 take_cached:
1681#endif
1682 ch = *i->p++;
1683 if (i->eof_flag && !*i->p)
1684 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001685 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001686 } else {
1687 /* need to double check i->file because we might be doing something
1688 * more complicated by now, like sourcing or substituting. */
1689#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001690 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001691 do {
1692 get_user_input(i);
1693 } while (!*i->p); /* need non-empty line */
1694 i->promptmode = 1; /* PS2 */
1695 i->promptme = 0;
1696 goto take_cached;
1697 }
1698#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001699 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001700 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001701 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001702#if ENABLE_HUSH_INTERACTIVE
1703 if (ch == '\n')
1704 i->promptme = 1;
1705#endif
1706 return ch;
1707}
1708
Denis Vlasenko913a2012009-04-05 22:17:04 +00001709/* All callers guarantee this routine will never
1710 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001711 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001712static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001713{
1714 int ch;
1715 if (i->p && *i->p) {
1716 if (i->eof_flag && !i->p[1])
1717 return EOF;
1718 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001719 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001720 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001721 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001722 i->eof_flag = (ch == EOF);
1723 i->peek_buf[0] = ch;
1724 i->peek_buf[1] = '\0';
1725 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001726 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001727 return ch;
1728}
1729
1730static void setup_file_in_str(struct in_str *i, FILE *f)
1731{
1732 i->peek = file_peek;
1733 i->get = file_get;
1734#if ENABLE_HUSH_INTERACTIVE
1735 i->promptme = 1;
1736 i->promptmode = 0; /* PS1 */
1737#endif
1738 i->file = f;
1739 i->p = NULL;
1740}
1741
1742static void setup_string_in_str(struct in_str *i, const char *s)
1743{
1744 i->peek = static_peek;
1745 i->get = static_get;
1746#if ENABLE_HUSH_INTERACTIVE
1747 i->promptme = 1;
1748 i->promptmode = 0; /* PS1 */
1749#endif
1750 i->p = s;
1751 i->eof_flag = 0;
1752}
1753
1754
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001755/*
1756 * o_string support
1757 */
1758#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001759
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001760static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001761{
1762 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001763 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001764 if (o->data)
1765 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001766}
1767
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001768static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001769{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001770 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001771 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001772}
1773
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001774static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1775{
1776 free(o->data);
1777}
1778
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001779static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001780{
1781 if (o->length + len > o->maxlen) {
1782 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1783 o->data = xrealloc(o->data, 1 + o->maxlen);
1784 }
1785}
1786
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001787static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001788{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001789 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1790 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001791 o->data[o->length] = ch;
1792 o->length++;
1793 o->data[o->length] = '\0';
1794}
1795
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001796static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001797{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001798 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001799 memcpy(&o->data[o->length], str, len);
1800 o->length += len;
1801 o->data[o->length] = '\0';
1802}
1803
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001804#if !BB_MMU
1805static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001806{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001807 o_addblock(o, str, strlen(str));
1808}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001809static void nommu_addchr(o_string *o, int ch)
1810{
1811 if (o)
1812 o_addchr(o, ch);
1813}
1814#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001815# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001816#endif
1817
1818static void o_addstr_with_NUL(o_string *o, const char *str)
1819{
1820 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001821}
1822
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001823static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001824{
1825 while (len) {
1826 o_addchr(o, *str);
1827 if (*str++ == '\\'
1828 && (*str != '*' && *str != '?' && *str != '[')
1829 ) {
1830 o_addchr(o, '\\');
1831 }
1832 len--;
1833 }
1834}
1835
Eric Andersen25f27032001-04-26 23:22:31 +00001836/* My analysis of quoting semantics tells me that state information
1837 * is associated with a destination, not a source.
1838 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001839static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001840{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001841 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001842 char *found = strchr("*?[\\", ch);
1843 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001844 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001845 o_grow_by(o, sz);
1846 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001847 o->data[o->length] = '\\';
1848 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001849 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001850 o->data[o->length] = ch;
1851 o->length++;
1852 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001853}
1854
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001855static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001856{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001857 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001858 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001859 sz++;
1860 o->data[o->length] = '\\';
1861 o->length++;
1862 }
1863 o_grow_by(o, sz);
1864 o->data[o->length] = ch;
1865 o->length++;
1866 o->data[o->length] = '\0';
1867}
1868
1869static void o_addQstr(o_string *o, const char *str, int len)
1870{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001871 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001872 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001873 return;
1874 }
1875 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001876 char ch;
1877 int sz;
1878 int ordinary_cnt = strcspn(str, "*?[\\");
1879 if (ordinary_cnt > len) /* paranoia */
1880 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001881 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001882 if (ordinary_cnt == len)
1883 return;
1884 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001885 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001886
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001887 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001888 sz = 1;
1889 if (ch) { /* it is necessarily one of "*?[\\" */
1890 sz++;
1891 o->data[o->length] = '\\';
1892 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001893 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001894 o_grow_by(o, sz);
1895 o->data[o->length] = ch;
1896 o->length++;
1897 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001898 }
1899}
1900
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001901/* A special kind of o_string for $VAR and `cmd` expansion.
1902 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001903 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001904 * list[i] contains an INDEX (int!) into this string data.
1905 * It means that if list[] needs to grow, data needs to be moved higher up
1906 * but list[i]'s need not be modified.
1907 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001908 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001909 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1910 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001911#if DEBUG_EXPAND || DEBUG_GLOB
1912static void debug_print_list(const char *prefix, o_string *o, int n)
1913{
1914 char **list = (char**)o->data;
1915 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1916 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001917
1918 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001919 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1920 prefix, list, n, string_start, o->length, o->maxlen);
1921 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001922 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001923 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1924 o->data + (int)list[i] + string_start,
1925 o->data + (int)list[i] + string_start);
1926 i++;
1927 }
1928 if (n) {
1929 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001930 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001931 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001932 }
1933}
1934#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001935# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001936#endif
1937
1938/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1939 * in list[n] so that it points past last stored byte so far.
1940 * It returns n+1. */
1941static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001942{
1943 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001944 int string_start;
1945 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001946
1947 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001948 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1949 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001950 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001951 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001952 /* list[n] points to string_start, make space for 16 more pointers */
1953 o->maxlen += 0x10 * sizeof(list[0]);
1954 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001955 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001956 memmove(list + n + 0x10, list + n, string_len);
1957 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001958 } else {
1959 debug_printf_list("list[%d]=%d string_start=%d\n",
1960 n, string_len, string_start);
1961 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001962 } else {
1963 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001964 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1965 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001966 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1967 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001968 o->has_empty_slot = 0;
1969 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001970 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001971 return n + 1;
1972}
1973
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001974/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001975static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001976{
1977 char **list = (char**)o->data;
1978 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1979
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001980 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001981}
1982
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001983/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001984 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001985static int o_glob(o_string *o, int n)
1986{
1987 glob_t globdata;
1988 int gr;
1989 char *pattern;
1990
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001991 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001992 if (!o->data)
1993 return o_save_ptr_helper(o, n);
1994 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001995 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001996 if (!glob_needed(pattern)) {
1997 literal:
1998 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001999 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002000 return o_save_ptr_helper(o, n);
2001 }
2002
2003 memset(&globdata, 0, sizeof(globdata));
2004 gr = glob(pattern, 0, NULL, &globdata);
2005 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2006 if (gr == GLOB_NOSPACE)
2007 bb_error_msg_and_die("out of memory during glob");
2008 if (gr == GLOB_NOMATCH) {
2009 globfree(&globdata);
2010 goto literal;
2011 }
2012 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002013 /* TODO: testcase for bad glob pattern behavior */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002014 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2015 }
2016 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2017 char **argv = globdata.gl_pathv;
2018 o->length = pattern - o->data; /* "forget" pattern */
2019 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002020 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002021 n = o_save_ptr_helper(o, n);
2022 argv++;
2023 if (!*argv)
2024 break;
2025 }
2026 }
2027 globfree(&globdata);
2028 if (DEBUG_GLOB)
2029 debug_print_list("o_glob returning", o, n);
2030 return n;
2031}
2032
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002033/* If o->o_glob == 1, glob the string so far remembered.
2034 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002035static int o_save_ptr(o_string *o, int n)
2036{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002037 if (o->o_glob) { /* if globbing is requested */
2038 /* If o->has_empty_slot, list[n] was already globbed
2039 * (if it was requested back then when it was filled)
2040 * so don't do that again! */
2041 if (!o->has_empty_slot)
2042 return o_glob(o, n); /* o_save_ptr_helper is inside */
2043 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002044 return o_save_ptr_helper(o, n);
2045}
2046
2047/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002048static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002049{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002050 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002051 int string_start;
2052
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002053 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2054 if (DEBUG_EXPAND)
2055 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002056 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002057 list = (char**)o->data;
2058 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2059 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002060 while (n) {
2061 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002062 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002063 }
2064 return list;
2065}
2066
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002067
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002068/* Expansion can recurse */
2069#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002070static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002071#endif
2072static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002073#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002074#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002075 parse_stream_dquoted(dest, input, dquote_end)
2076#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002077static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002078 o_string *dest,
2079 struct in_str *input,
2080 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002081
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002082/* expand_strvec_to_strvec() takes a list of strings, expands
2083 * all variable references within and returns a pointer to
2084 * a list of expanded strings, possibly with larger number
2085 * of strings. (Think VAR="a b"; echo $VAR).
2086 * This new list is allocated as a single malloc block.
2087 * NULL-terminated list of char* pointers is at the beginning of it,
2088 * followed by strings themself.
2089 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002090
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002091/* Store given string, finalizing the word and starting new one whenever
2092 * we encounter IFS char(s). This is used for expanding variable values.
2093 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2094static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002095{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002096 while (1) {
2097 int word_len = strcspn(str, G.ifs);
2098 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002099 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002100 o_addQstr(output, str, word_len);
2101 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002102 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002103 str += word_len;
2104 }
2105 if (!*str) /* EOL - do not finalize word */
2106 break;
2107 o_addchr(output, '\0');
2108 debug_print_list("expand_on_ifs", output, n);
2109 n = o_save_ptr(output, n);
2110 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002111 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002112 debug_print_list("expand_on_ifs[1]", output, n);
2113 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002114}
2115
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002116/* Helper to expand $((...)) and heredoc body. These act as if
2117 * they are in double quotes, with the exception that they are not :).
2118 * Just the rules are similar: "expand only $var and `cmd`"
2119 *
2120 * Returns malloced string.
2121 * As an optimization, we return NULL if expansion is not needed.
2122 */
2123static char *expand_pseudo_dquoted(const char *str)
2124{
2125 char *exp_str;
2126 struct in_str input;
2127 o_string dest = NULL_O_STRING;
2128
2129 if (strchr(str, '$') == NULL
2130#if ENABLE_HUSH_TICK
2131 && strchr(str, '`') == NULL
2132#endif
2133 ) {
2134 return NULL;
2135 }
2136
2137 /* We need to expand. Example:
2138 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2139 */
2140 setup_string_in_str(&input, str);
2141 parse_stream_dquoted(NULL, &dest, &input, EOF);
2142 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2143 exp_str = expand_string_to_string(dest.data);
2144 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2145 o_free_unsafe(&dest);
2146 return exp_str;
2147}
2148
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002149/* Expand all variable references in given string, adding words to list[]
2150 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2151 * to be filled). This routine is extremely tricky: has to deal with
2152 * variables/parameters with whitespace, $* and $@, and constructs like
2153 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2154static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002155{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002156 /* or_mask is either 0 (normal case) or 0x80 -
2157 * expansion of right-hand side of assignment == 1-element expand.
2158 * It will also do no globbing, and thus we must not backslash-quote!
2159 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002160 char ored_ch;
2161 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002162
2163 ored_ch = 0;
2164
2165 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2166 debug_print_list("expand_vars_to_list", output, n);
2167 n = o_save_ptr(output, n);
2168 debug_print_list("expand_vars_to_list[0]", output, n);
2169
2170 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002171 char first_ch;
2172 int i;
2173 char *dyn_val = NULL;
2174 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002175#if ENABLE_HUSH_TICK
2176 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002177#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002178#if ENABLE_SH_MATH_SUPPORT
2179 char arith_buf[sizeof(arith_t)*3 + 2];
2180#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002181 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002182 debug_print_list("expand_vars_to_list[1]", output, n);
2183 arg = ++p;
2184 p = strchr(p, SPECIAL_VAR_SYMBOL);
2185
2186 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2187 /* "$@" is special. Even if quoted, it can still
2188 * expand to nothing (not even an empty string) */
2189 if ((first_ch & 0x7f) != '@')
2190 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002191
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002192 switch (first_ch & 0x7f) {
2193 /* Highest bit in first_ch indicates that var is double-quoted */
2194 case '$': /* pid */
2195 val = utoa(G.root_pid);
2196 break;
2197 case '!': /* bg pid */
2198 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2199 break;
2200 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002201 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202 break;
2203 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002204 if (arg[1] != SPECIAL_VAR_SYMBOL)
2205 /* actually, it's a ${#var} */
2206 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002207 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2208 break;
2209 case '*':
2210 case '@':
2211 i = 1;
2212 if (!G.global_argv[i])
2213 break;
2214 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2215 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002216 smallint sv = output->o_escape;
2217 /* unquoted var's contents should be globbed, so don't escape */
2218 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002219 while (G.global_argv[i]) {
2220 n = expand_on_ifs(output, n, G.global_argv[i]);
2221 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2222 if (G.global_argv[i++][0] && G.global_argv[i]) {
2223 /* this argv[] is not empty and not last:
2224 * put terminating NUL, start new word */
2225 o_addchr(output, '\0');
2226 debug_print_list("expand_vars_to_list[2]", output, n);
2227 n = o_save_ptr(output, n);
2228 debug_print_list("expand_vars_to_list[3]", output, n);
2229 }
2230 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002231 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002232 } else
2233 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2234 * and in this case should treat it like '$*' - see 'else...' below */
2235 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2236 while (1) {
2237 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2238 if (++i >= G.global_argc)
2239 break;
2240 o_addchr(output, '\0');
2241 debug_print_list("expand_vars_to_list[4]", output, n);
2242 n = o_save_ptr(output, n);
2243 }
2244 } else { /* quoted $*: add as one word */
2245 while (1) {
2246 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2247 if (!G.global_argv[++i])
2248 break;
2249 if (G.ifs[0])
2250 o_addchr(output, G.ifs[0]);
2251 }
2252 }
2253 break;
2254 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2255 /* "Empty variable", used to make "" etc to not disappear */
2256 arg++;
2257 ored_ch = 0x80;
2258 break;
2259#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002260 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002261 *p = '\0';
2262 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002263 /* Can't just stuff it into output o_string,
2264 * expanded result may need to be globbed
2265 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002267 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002268 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2269 val = subst_result.data;
2270 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002271#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002272#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002273 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002274 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002275 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002276 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002277 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002278
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002279 arg++; /* skip '+' */
2280 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002281 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002282
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002283 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002284 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002285 hooks.setvar = arith_set_local_var;
2286 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002287 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2288 free(exp_str);
2289
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002290 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002291 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002292 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002293 case -3:
2294 msg = "exponent less than 0";
2295 break;
2296 case -2:
2297 msg = "divide by 0";
2298 break;
2299 case -5:
2300 msg = "expression recursion loop detected";
2301 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002302 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002303 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002304 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002305 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002306 sprintf(arith_buf, arith_t_fmt, res);
2307 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002308 break;
2309 }
2310#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002311 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002312 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002313 bool exp_len = false;
2314 bool exp_null = false;
2315 char *var = arg;
2316 char exp_save = exp_save; /* for compiler */
2317 char exp_op = exp_op; /* for compiler */
2318 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002319 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002320
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002321 *p = '\0';
2322 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002323
2324 /* prepare for expansions */
2325 if (var[0] == '#') {
2326 /* handle length expansion ${#var} */
2327 exp_len = true;
2328 ++var;
2329 } else {
2330 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002331 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002332 if (!var[exp_off])
2333 exp_off = 0;
2334 if (exp_off) {
2335 exp_save = var[exp_off];
2336 exp_null = exp_save == ':';
2337 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002338 if (exp_null)
2339 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002340 exp_op = *exp_word++;
2341 var[exp_off] = '\0';
2342 }
2343 }
2344
2345 /* lookup the variable in question */
2346 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002347 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002348 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002349 if (i < G.global_argc)
2350 val = G.global_argv[i];
2351 /* else val remains NULL: $N with too big N */
2352 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002353 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002354
2355 /* handle any expansions */
2356 if (exp_len) {
2357 debug_printf_expand("expand: length of '%s' = ", val);
2358 val = utoa(val ? strlen(val) : 0);
2359 debug_printf_expand("%s\n", val);
2360 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002361 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002362 if (val) {
2363 /* we need to do a pattern match */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002364 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002365 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002366 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002367 if (exp_op == *exp_word) /* ## or %% */
2368 ++exp_word;
2369 val = dyn_val = xstrdup(val);
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002370 loc = scan(dyn_val, exp_word, match_at_left);
2371 if (match_at_left) /* # or ## */
Mike Frysinger57e74672009-04-09 23:00:33 +00002372 val = loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002373 else if (loc) /* % or %% and match was found */
Mike Frysinger57e74672009-04-09 23:00:33 +00002374 *loc = '\0';
2375 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002376 } else {
2377 /* we need to do an expansion */
2378 int exp_test = (!val || (exp_null && !val[0]));
2379 if (exp_op == '+')
2380 exp_test = !exp_test;
2381 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2382 exp_null ? "true" : "false", exp_test);
2383 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002384 if (exp_op == '?') {
2385//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002386 /* ${var?[error_msg_if_unset]} */
2387 /* ${var:?[error_msg_if_unset_or_null]} */
2388 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002389 die_if_script("%s: %s",
2390 var,
2391 exp_word[0] ? exp_word : "parameter null or not set"
2392 );
2393 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002394 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002395 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002396
Mike Frysingera4f331d2009-04-07 06:03:22 +00002397 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002398 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002399 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002400 /* mimic bash message */
2401 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002402 val = NULL;
2403 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002404 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002405 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002406 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002407 }
2408 }
2409 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002410
Mike Frysinger6379bb42009-03-28 18:55:03 +00002411 var[exp_off] = exp_save;
2412 }
2413
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002414 arg[0] = first_ch;
2415#if ENABLE_HUSH_TICK
2416 store_val:
2417#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002418 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002419 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002420 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002421 /* unquoted var's contents should be globbed, so don't escape */
2422 smallint sv = output->o_escape;
2423 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002424 n = expand_on_ifs(output, n, val);
2425 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002426 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002427 }
2428 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002429 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002430 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002431 } /* default: */
2432 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002433
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002434 if (val) {
2435 o_addQstr(output, val, strlen(val));
2436 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002437 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002438 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002439 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002440 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002441
2442#if ENABLE_HUSH_TICK
2443 o_free(&subst_result);
2444#endif
2445 arg = ++p;
2446 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2447
2448 if (arg[0]) {
2449 debug_print_list("expand_vars_to_list[a]", output, n);
2450 /* this part is literal, and it was already pre-quoted
2451 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002452 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002453 debug_print_list("expand_vars_to_list[b]", output, n);
2454 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2455 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2456 ) {
2457 n--;
2458 /* allow to reuse list[n] later without re-growth */
2459 output->has_empty_slot = 1;
2460 } else {
2461 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002462 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002463 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002464}
2465
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002466static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002467{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002468 int n;
2469 char **list;
2470 char **v;
2471 o_string output = NULL_O_STRING;
2472
2473 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002474 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002475 /* (unquoted $var will temporarily switch it off) */
2476 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002477 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002478
2479 n = 0;
2480 v = argv;
2481 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002482 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483 v++;
2484 }
2485 debug_print_list("expand_variables", &output, n);
2486
2487 /* output.data (malloced in one block) gets returned in "list" */
2488 list = o_finalize_list(&output, n);
2489 debug_print_strings("expand_variables[1]", list);
2490 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002491}
2492
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002493static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002494{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002495 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002496}
2497
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002498#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002499static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2500{
2501 return expand_variables(argv, 0x80);
2502}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002503#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002504
2505#ifdef CMD_SINGLEWORD_NOGLOB_COND
2506static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2507{
2508 int n;
2509 char **list;
2510 char **v;
2511 o_string output = NULL_O_STRING;
2512
2513 n = 0;
2514 v = argv;
2515 while (*v) {
2516 int is_var = is_well_formed_var_name(*v, '=');
2517 /* is_var * 0x80: singleword expansion for vars */
2518 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2519
2520 /* Subtle! expand_vars_to_list did not glob last word yet.
2521 * It does this only when fed with further data.
2522 * Therefore we set globbing flags AFTER it, not before:
2523 */
2524
2525 /* if it is not recognizably abc=...; then: */
2526 output.o_escape = !is_var; /* protect against globbing for "$var" */
2527 /* (unquoted $var will temporarily switch it off) */
2528 output.o_glob = !is_var; /* and indeed do globbing */
2529 v++;
2530 }
2531 debug_print_list("expand_cond", &output, n);
2532
2533 /* output.data (malloced in one block) gets returned in "list" */
2534 list = o_finalize_list(&output, n);
2535 debug_print_strings("expand_cond[1]", list);
2536 return list;
2537}
2538#endif
2539
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002540/* Used for expansion of right hand of assignments */
2541/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2542 * "v=/bin/c*" */
2543static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002544{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002545 char *argv[2], **list;
2546
2547 argv[0] = (char*)str;
2548 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002549 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002550 if (HUSH_DEBUG)
2551 if (!list[0] || list[1])
2552 bb_error_msg_and_die("BUG in varexp2");
2553 /* actually, just move string 2*sizeof(char*) bytes back */
2554 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002555 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2557 return (char*)list;
2558}
2559
2560/* Used for "eval" builtin */
2561static char* expand_strvec_to_string(char **argv)
2562{
2563 char **list;
2564
2565 list = expand_variables(argv, 0x80);
2566 /* Convert all NULs to spaces */
2567 if (list[0]) {
2568 int n = 1;
2569 while (list[n]) {
2570 if (HUSH_DEBUG)
2571 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2572 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002573 /* bash uses ' ' regardless of $IFS contents */
2574 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002575 n++;
2576 }
2577 }
2578 overlapping_strcpy((char*)list, list[0]);
2579 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2580 return (char*)list;
2581}
2582
2583static char **expand_assignments(char **argv, int count)
2584{
2585 int i;
2586 char **p = NULL;
2587 /* Expand assignments into one string each */
2588 for (i = 0; i < count; i++) {
2589 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2590 }
2591 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002592}
2593
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002594
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002595#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002596/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002597void re_execute_shell(char ***to_free, const char *s,
2598 char *g_argv0, char **g_argv,
2599 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002600
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002601static void reset_traps_to_defaults(void)
2602{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002603 /* This function is always called in a child shell
2604 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002605 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002606 unsigned sig;
2607 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002608
Denys Vlasenko67f71862009-09-25 14:21:06 +02002609 /* Child shells are not interactive.
2610 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2611 * Testcase: (while :; do :; done) + ^Z should background.
2612 * Same goes for SIGTERM, SIGHUP, SIGINT.
2613 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002614 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02002615 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002616
Denys Vlasenko67f71862009-09-25 14:21:06 +02002617 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2618 * Stupid. It can be done with *single* &= op, but we can't use
2619 * the fact that G.blocked_set is implemented as a bitmask
2620 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002621 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2622 sig = 1;
2623 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002624 if (mask & 1) {
2625 /* Careful. Only if no trap or trap is not "" */
2626 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2627 sigdelset(&G.blocked_set, sig);
2628 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002629 mask >>= 1;
2630 if (!mask)
2631 break;
2632 sig++;
2633 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02002634 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002635 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002636
2637 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002638 mask = G.non_DFL_mask;
2639 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002640 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002641 continue;
2642 free(G.traps[sig]);
2643 G.traps[sig] = NULL;
2644 /* There is no signal for 0 (EXIT) */
2645 if (sig == 0)
2646 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002647 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002648 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02002649 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002650 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002651 continue;
2652 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002653 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002654 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002655}
2656
2657#else /* !BB_MMU */
2658
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002659static void re_execute_shell(char ***to_free, const char *s,
2660 char *g_argv0, char **g_argv,
2661 char **builtin_argv) NORETURN;
2662static void re_execute_shell(char ***to_free, const char *s,
2663 char *g_argv0, char **g_argv,
2664 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002665{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002666 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002667 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002668 struct variable *cur;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002669#if ENABLE_HUSH_FUNCTIONS
2670 struct function *funcp;
2671#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002672 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002673 unsigned cnt;
2674
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002675 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002676 argv = heredoc_argv;
2677 argv[0] = (char *) G.argv0_for_re_execing;
2678 argv[1] = (char *) "-<";
2679 argv[2] = (char *) s;
2680 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002681 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002682 goto do_exec;
2683 }
2684
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002685 cnt = 0;
2686 pp = builtin_argv;
2687 if (pp) while (*pp++)
2688 cnt++;
2689
2690 sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002691 , (unsigned) G.root_pid
2692 , (unsigned) G.last_bg_pid
2693 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002694 , cnt
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002695 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002696 );
Denis Vlasenkobc569742009-04-12 20:35:19 +00002697 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002698 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002699 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002700 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002701 for (cur = G.top_var; cur; cur = cur->next) {
2702 if (!cur->flg_export || cur->flg_read_only)
2703 cnt += 2;
2704 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002705#if ENABLE_HUSH_FUNCTIONS
2706 for (funcp = G.top_func; funcp; funcp = funcp->next)
2707 cnt += 3;
2708#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002709 pp = g_argv;
2710 while (*pp++)
2711 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002712 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002713 *pp++ = (char *) G.argv0_for_re_execing;
2714 *pp++ = param_buf;
2715 for (cur = G.top_var; cur; cur = cur->next) {
2716 if (cur->varstr == hush_version_str)
2717 continue;
2718 if (cur->flg_read_only) {
2719 *pp++ = (char *) "-R";
2720 *pp++ = cur->varstr;
2721 } else if (!cur->flg_export) {
2722 *pp++ = (char *) "-V";
2723 *pp++ = cur->varstr;
2724 }
2725 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002726#if ENABLE_HUSH_FUNCTIONS
2727 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2728 *pp++ = (char *) "-F";
2729 *pp++ = funcp->name;
2730 *pp++ = funcp->body_as_string;
2731 }
2732#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002733 /* We can pass activated traps here. Say, -Tnn:trap_string
2734 *
2735 * However, POSIX says that subshells reset signals with traps
2736 * to SIG_DFL.
2737 * I tested bash-3.2 and it not only does that with true subshells
2738 * of the form ( list ), but with any forked children shells.
2739 * I set trap "echo W" WINCH; and then tried:
2740 *
2741 * { echo 1; sleep 20; echo 2; } &
2742 * while true; do echo 1; sleep 20; echo 2; break; done &
2743 * true | { echo 1; sleep 20; echo 2; } | cat
2744 *
2745 * In all these cases sending SIGWINCH to the child shell
2746 * did not run the trap. If I add trap "echo V" WINCH;
2747 * _inside_ group (just before echo 1), it works.
2748 *
2749 * I conclude it means we don't need to pass active traps here.
2750 * exec syscall below resets them to SIG_DFL for us.
2751 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002752 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002753 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002754 if (builtin_argv) {
2755 while (*++builtin_argv)
2756 *pp++ = *builtin_argv;
2757 *pp++ = (char *) "";
2758 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002759 *pp++ = g_argv0;
2760 while (*g_argv)
2761 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002762 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002763 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002764
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002765 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002766 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2767 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002768 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002769 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002770 if (argv[0][0] == '/')
2771 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002772 xfunc_error_retval = 127;
2773 bb_error_msg_and_die("can't re-execute the shell");
2774}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002775#endif /* !BB_MMU */
2776
2777
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002778static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002779{
2780 struct fd_pair pair;
2781 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002782 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002783 /* the _body_ of heredoc (misleading field name) */
2784 const char *heredoc = redir->rd_filename;
2785 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002786#if !BB_MMU
2787 char **to_free;
2788#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002789
2790 expanded = NULL;
2791 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2792 expanded = expand_pseudo_dquoted(heredoc);
2793 if (expanded)
2794 heredoc = expanded;
2795 }
2796 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002797
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002798 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002799 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002800 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002801
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002802 /* Try writing without forking. Newer kernels have
2803 * dynamically growing pipes. Must use non-blocking write! */
2804 ndelay_on(pair.wr);
2805 while (1) {
2806 written = write(pair.wr, heredoc, len);
2807 if (written <= 0)
2808 break;
2809 len -= written;
2810 if (len == 0) {
2811 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002812 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002813 return;
2814 }
2815 heredoc += written;
2816 }
2817 ndelay_off(pair.wr);
2818
2819 /* Okay, pipe buffer was not big enough */
2820 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002821 * for the unsuspecting parent process. Child creates a grandchild
2822 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002823 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002824#if !BB_MMU
2825 to_free = NULL;
2826#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002827 pid = vfork();
2828 if (pid < 0)
2829 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002830 if (pid == 0) {
2831 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002832 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002833 pid = BB_MMU ? fork() : vfork();
2834 if (pid < 0)
2835 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2836 if (pid != 0)
2837 _exit(0);
2838 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002839 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002840#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002841 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002842 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002843#else
2844 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002845 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002846 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002847#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002848 }
2849 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02002850#if ENABLE_HUSH_FAST
2851 G.count_SIGCHLD++;
2852//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2853#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002854 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002855#if !BB_MMU
2856 free(to_free);
2857#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002858 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002859 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002860 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002861}
2862
Eric Andersen25f27032001-04-26 23:22:31 +00002863/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2864 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002865static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002866{
2867 int openfd, mode;
2868 struct redir_struct *redir;
2869
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002870 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002871 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002872 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02002873 if (squirrel && redir->rd_fd < 3
2874 && squirrel[redir->rd_fd] < 0
2875 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002876 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002877 }
2878 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2879 * of the heredoc */
2880 debug_printf_parse("set heredoc '%s'\n",
2881 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002882 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00002883 continue;
2884 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002885
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002886 if (redir->rd_dup == REDIRFD_TO_FILE) {
2887 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002888 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002889 if (redir->rd_filename == NULL) {
2890 /* Something went wrong in the parse.
2891 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002892 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002893 continue;
2894 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002895 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002896 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002897 openfd = open_or_warn(p, mode);
2898 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002899 if (openfd < 0) {
2900 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002901 * bash and ash both lose it as well (though zsh doesn't!) */
2902//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00002903 return 1;
2904 }
2905 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002906 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002907 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00002908 }
2909
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002910 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02002911 if (squirrel && redir->rd_fd < 3
2912 && squirrel[redir->rd_fd] < 0
2913 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002914 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00002915 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002916 if (openfd == REDIRFD_CLOSE) {
2917 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002918 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002919 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002920 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002921 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002922 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002923 }
Eric Andersen25f27032001-04-26 23:22:31 +00002924 }
2925 }
2926 return 0;
2927}
2928
2929static void restore_redirects(int squirrel[])
2930{
2931 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002932 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002933 fd = squirrel[i];
2934 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002935 /* We simply die on error */
2936 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002937 }
2938 }
2939}
2940
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002941
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002942static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002943
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002944/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002945static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002946{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002947 char **p;
2948 struct command *command;
2949 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002950 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002951
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002952 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002953 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002954 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002955 for (i = 0; i < pi->num_cmds; i++) {
2956 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002957 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002958 if (command->argv) {
2959 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002960 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002961 }
2962 free_strings(command->argv);
2963 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002964 }
2965 /* not "else if": on syntax error, we may have both! */
2966 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002967 debug_printf_clean(" begin group (cmd_type:%d)\n",
2968 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002969 free_pipe_list(command->group);
2970 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002971 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002972 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002973 /* else is crucial here.
2974 * If group != NULL, child_func is meaningless */
2975#if ENABLE_HUSH_FUNCTIONS
2976 else if (command->child_func) {
2977 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2978 command->child_func->parent_cmd = NULL;
2979 }
2980#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002981#if !BB_MMU
2982 free(command->group_as_string);
2983 command->group_as_string = NULL;
2984#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002985 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002986 debug_printf_clean(" redirect %d%s",
2987 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002988 /* guard against the case >$FOO, where foo is unset or blank */
2989 if (r->rd_filename) {
2990 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2991 free(r->rd_filename);
2992 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002993 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002994 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002995 rnext = r->next;
2996 free(r);
2997 }
2998 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002999 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003000 free(pi->cmds); /* children are an array, they get freed all at once */
3001 pi->cmds = NULL;
3002#if ENABLE_HUSH_JOB
3003 free(pi->cmdtext);
3004 pi->cmdtext = NULL;
3005#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003006}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003007
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003008static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003009{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003010 struct pipe *pi, *next;
3011
3012 for (pi = head; pi; pi = next) {
3013#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003014 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003015#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003016 free_pipe(pi);
3017 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003018 next = pi->next;
3019 /*pi->next = NULL;*/
3020 free(pi);
3021 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003022}
3023
3024
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003025static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003026#if BB_MMU
3027#define parse_stream(pstring, input, end_trigger) \
3028 parse_stream(input, end_trigger)
3029#endif
3030static struct pipe *parse_stream(char **pstring,
3031 struct in_str *input,
3032 int end_trigger);
3033static void parse_and_run_string(const char *s);
3034
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003035
Mike Frysinger93cadc22009-05-27 17:06:25 -04003036static char *find_in_path(const char *arg)
3037{
3038 char *ret = NULL;
3039 const char *PATH = get_local_var_value("PATH");
3040
3041 if (!PATH)
3042 return NULL;
3043
3044 while (1) {
3045 const char *end = strchrnul(PATH, ':');
3046 int sz = end - PATH; /* must be int! */
3047
3048 free(ret);
3049 if (sz != 0) {
3050 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3051 } else {
3052 /* We have xxx::yyyy in $PATH,
3053 * it means "use current dir" */
3054 ret = xstrdup(arg);
3055 }
3056 if (access(ret, F_OK) == 0)
3057 break;
3058
3059 if (*end == '\0') {
3060 free(ret);
3061 return NULL;
3062 }
3063 PATH = end + 1;
3064 }
3065
3066 return ret;
3067}
3068
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003069static const struct built_in_command* find_builtin_helper(const char *name,
3070 const struct built_in_command *x,
3071 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003072{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003073 while (x != end) {
3074 if (strcmp(name, x->cmd) != 0) {
3075 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003076 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003077 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003078 debug_printf_exec("found builtin '%s'\n", name);
3079 return x;
3080 }
3081 return NULL;
3082}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003083static const struct built_in_command* find_builtin1(const char *name)
3084{
3085 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3086}
3087static const struct built_in_command* find_builtin(const char *name)
3088{
3089 const struct built_in_command *x = find_builtin1(name);
3090 if (x)
3091 return x;
3092 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3093}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003094
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003095#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003096static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003097{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003098 struct function **funcpp = &G.top_func;
3099 while (*funcpp) {
3100 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003101 break;
3102 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003103 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003104 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003105 return funcpp;
3106}
3107
3108static const struct function *find_function(const char *name)
3109{
3110 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003111 if (funcp)
3112 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003113 return funcp;
3114}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003115
Denis Vlasenkobc569742009-04-12 20:35:19 +00003116/* Note: takes ownership on name ptr */
3117static struct function *new_function(char *name)
3118{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003119 struct function **funcpp = find_function_slot(name);
3120 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003121
Denys Vlasenko873273d2009-09-12 14:47:41 +02003122 if (funcp != NULL) {
3123 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003124 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3125 if (!cmd) {
3126 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3127 free(funcp->name);
3128 /* Note: if !funcp->body, do not free body_as_string!
3129 * This is a special case of "-F name body" function:
3130 * body_as_string was not malloced! */
3131 if (funcp->body) {
3132 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003133# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003134 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003135# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003136 }
3137 } else {
3138 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3139 cmd->argv[0] = funcp->name;
3140 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003141# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003142 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003143# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003144 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003145 } else {
3146 debug_printf_exec("remembering new function '%s'\n", name);
3147 funcp = *funcpp = xzalloc(sizeof(*funcp));
3148 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003149 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003150
Denis Vlasenkobc569742009-04-12 20:35:19 +00003151 funcp->name = name;
3152 return funcp;
3153}
3154
Denis Vlasenko40e84372009-04-18 11:23:38 +00003155static void unset_func(const char *name)
3156{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003157 struct function **funcpp = find_function_slot(name);
3158 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003159
Denys Vlasenko873273d2009-09-12 14:47:41 +02003160 if (funcp != NULL) {
3161 debug_printf_exec("freeing function '%s'\n", funcp->name);
3162 *funcpp = funcp->next;
3163 /* funcp is unlinked now, deleting it.
3164 * Note: if !funcp->body, the function was created by
3165 * "-F name body", do not free ->body_as_string
3166 * and ->name as they were not malloced. */
3167 if (funcp->body) {
3168 free_pipe_list(funcp->body);
3169 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003170# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003171 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003172# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003173 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003174 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003175 }
3176}
3177
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003178# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003179#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003180 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003181# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003182static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003183 const struct function *funcp,
3184 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003185static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003186 const struct function *funcp,
3187 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003188{
3189# if BB_MMU
3190 int n = 1;
3191
3192 argv[0] = G.global_argv[0];
3193 G.global_argv = argv;
3194 while (*++argv)
3195 n++;
3196 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003197 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003198 n = run_list(funcp->body);
3199 fflush(NULL);
3200 _exit(n);
3201# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003202 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003203 funcp->body_as_string,
3204 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003205 argv + 1,
3206 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003207# endif
3208}
3209
3210static int run_function(const struct function *funcp, char **argv)
3211{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003212 int rc;
3213 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003214 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003215
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003216 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003217
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003218 /* "we are in function, ok to use return" */
3219 sv_flg = G.flag_return_in_progress;
3220 G.flag_return_in_progress = -1;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003221#if ENABLE_HUSH_LOCAL
3222 G.func_nest_level++;
3223#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003224
Denis Vlasenkobc569742009-04-12 20:35:19 +00003225 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003226# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003227 if (!funcp->body) {
3228 /* Function defined by -F */
3229 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003230 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003231 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003232# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003233 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003234 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003235 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003236
Denys Vlasenko295fef82009-06-03 12:47:26 +02003237#if ENABLE_HUSH_LOCAL
3238 {
3239 struct variable *var;
3240 struct variable **var_pp;
3241
3242 var_pp = &G.top_var;
3243 while ((var = *var_pp) != NULL) {
3244 if (var->func_nest_level < G.func_nest_level) {
3245 var_pp = &var->next;
3246 continue;
3247 }
3248 /* Unexport */
3249 if (var->flg_export)
3250 bb_unsetenv(var->varstr);
3251 /* Remove from global list */
3252 *var_pp = var->next;
3253 /* Free */
3254 if (!var->max_len)
3255 free(var->varstr);
3256 free(var);
3257 }
3258 G.func_nest_level--;
3259 }
3260#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003261 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003262
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003263 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003264
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003265 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003266}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003267#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003268
3269
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003270# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003271#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003272 exec_builtin(x, argv)
3273# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003274#define exec_builtin(to_free, x, argv) \
3275 exec_builtin(to_free, argv)
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003276# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003277static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003278 const struct built_in_command *x,
3279 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003280static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003281 const struct built_in_command *x,
3282 char **argv)
3283{
3284# if BB_MMU
3285 int rcode = x->function(argv);
3286 fflush(NULL);
3287 _exit(rcode);
3288# else
3289 /* On NOMMU, we must never block!
3290 * Example: { sleep 99 | read line; } & echo Ok
3291 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003292 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003293 argv[0],
3294 G.global_argv[0],
3295 G.global_argv + 1,
3296 argv);
3297# endif
3298}
3299
3300
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003301#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003302#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3303 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3304#define pseudo_exec(nommu_save, command, argv_expanded) \
3305 pseudo_exec(command, argv_expanded)
3306#endif
3307
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003308/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003309 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003310 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003311 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003312 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003313static void pseudo_exec_argv(nommu_save_t *nommu_save,
3314 char **argv, int assignment_cnt,
3315 char **argv_expanded) NORETURN;
3316static void pseudo_exec_argv(nommu_save_t *nommu_save,
3317 char **argv, int assignment_cnt,
3318 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003319{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003320 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003321
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003322 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003323 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003324 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003325
Denis Vlasenko9504e442008-10-29 01:19:15 +00003326 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003327#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003328 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003329 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003330 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003331 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003332#else
3333 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003334 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003335#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003336 if (argv_expanded) {
3337 argv = argv_expanded;
3338 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003339 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003340#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003341 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003342#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003343 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003344
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003345#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3346 if (strchr(argv[0], '/') != NULL)
3347 goto skip;
3348#endif
3349
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003350 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003351 * Depending on context, this might be redundant. But it's
3352 * easier to waste a few CPU cycles than it is to figure out
3353 * if this is one of those cases.
3354 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003355 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003356 /* On NOMMU, it is more expensive to re-execute shell
3357 * just in order to run echo or test builtin.
3358 * It's better to skip it here and run corresponding
3359 * non-builtin later. */
3360 const struct built_in_command *x;
3361 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003362 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003363 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003364 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003365 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003366#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003367 /* Check if the command matches any functions */
3368 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003369 const struct function *funcp = find_function(argv[0]);
3370 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003371 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003372 }
3373 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003374#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003375
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003376#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003377 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003378 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003379 int a = find_applet_by_name(argv[0]);
3380 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003381# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003382 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003383 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003384 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003385 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003386# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003387 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003388 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003389 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3390 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003391 /* If they called chroot or otherwise made the binary no longer
3392 * executable, fall through */
3393 }
3394 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003395#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003396
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003397#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003398 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003399#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003400 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003401 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003402 execvp(argv[0], argv);
Denis Vlasenkof9d4fc32009-04-21 20:40:51 +00003403 bb_perror_msg("can't execute '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00003404 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003405}
3406
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003407/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003408 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003409static void pseudo_exec(nommu_save_t *nommu_save,
3410 struct command *command,
3411 char **argv_expanded) NORETURN;
3412static void pseudo_exec(nommu_save_t *nommu_save,
3413 struct command *command,
3414 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003415{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003416 if (command->argv) {
3417 pseudo_exec_argv(nommu_save, command->argv,
3418 command->assignment_cnt, argv_expanded);
3419 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003420
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003421 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003422 /* Cases when we are here:
3423 * ( list )
3424 * { list } &
3425 * ... | ( list ) | ...
3426 * ... | { list } | ...
3427 */
3428#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003429 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003430 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003431 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003432 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003433 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003434 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003435 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003436#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003437 re_execute_shell(&nommu_save->argv_from_re_execing,
3438 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003439 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003440 G.global_argv + 1,
3441 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003442#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003443 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003444
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003445 /* Case when we are here: ... | >file */
3446 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003447 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003448}
3449
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003450#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003451static const char *get_cmdtext(struct pipe *pi)
3452{
3453 char **argv;
3454 char *p;
3455 int len;
3456
3457 /* This is subtle. ->cmdtext is created only on first backgrounding.
3458 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003459 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003460 if (pi->cmdtext)
3461 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003462 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003463 if (!argv || !argv[0]) {
3464 pi->cmdtext = xzalloc(1);
3465 return pi->cmdtext;
3466 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003467
3468 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003469 do {
3470 len += strlen(*argv) + 1;
3471 } while (*++argv);
3472 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003473 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003474 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003475 do {
3476 len = strlen(*argv);
3477 memcpy(p, *argv, len);
3478 p += len;
3479 *p++ = ' ';
3480 } while (*++argv);
3481 p[-1] = '\0';
3482 return pi->cmdtext;
3483}
3484
Eric Andersenbafd94f2001-05-02 16:11:59 +00003485static void insert_bg_job(struct pipe *pi)
3486{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003487 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003488 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003489
3490 /* Linear search for the ID of the job to use */
3491 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003492 for (job = G.job_list; job; job = job->next)
3493 if (job->jobid >= pi->jobid)
3494 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003495
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003496 /* Add job to the list of running jobs */
3497 jobp = &G.job_list;
3498 while ((job = *jobp) != NULL)
3499 jobp = &job->next;
3500 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003501
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003502 *job = *pi; /* physical copy */
3503 job->next = NULL;
3504 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3505 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003506 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003507 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003508 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003509 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003510 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003511
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003512 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003513 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3514 /* Last command's pid goes to $! */
3515 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3516 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003517}
3518
Eric Andersenbafd94f2001-05-02 16:11:59 +00003519static void remove_bg_job(struct pipe *pi)
3520{
3521 struct pipe *prev_pipe;
3522
Denis Vlasenko87a86552008-07-29 19:43:10 +00003523 if (pi == G.job_list) {
3524 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003525 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003526 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003527 while (prev_pipe->next != pi)
3528 prev_pipe = prev_pipe->next;
3529 prev_pipe->next = pi->next;
3530 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003531 if (G.job_list)
3532 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003533 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003534 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003535}
Eric Andersen028b65b2001-06-28 01:10:11 +00003536
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003537/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003538static void delete_finished_bg_job(struct pipe *pi)
3539{
3540 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003541 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003542 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003543 free(pi);
3544}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003545#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003546
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003547/* Check to see if any processes have exited -- if they
3548 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003549static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003550{
Eric Andersenc798b072001-06-22 06:23:03 +00003551 int attributes;
3552 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003553#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003554 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003555#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003556 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003557 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003558
Denis Vlasenkod5762932009-03-31 11:22:57 +00003559 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3560
Eric Andersenc798b072001-06-22 06:23:03 +00003561 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003562 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003563 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003564
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003565 errno = 0;
3566#if ENABLE_HUSH_FAST
3567 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3568//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3569//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003570 /* There was neither fork nor SIGCHLD since last waitpid */
3571 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003572 if (!G.we_have_children) {
3573 errno = ECHILD;
3574 return -1;
3575 }
3576 if (fg_pipe == NULL) { /* is WNOHANG set? */
3577 /* We have children, but they did not exit
3578 * or stop yet (we saw no SIGCHLD) */
3579 return 0;
3580 }
3581 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3582 }
3583#endif
3584
Denis Vlasenko1359da62007-04-21 23:27:30 +00003585/* Do we do this right?
3586 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003587 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003588 * [3]+ Stopped sleep 20 | false
3589 * bash-3.00# echo $?
3590 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003591 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003592 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003593 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003594 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003595 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003596 int dead;
3597
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003598#if ENABLE_HUSH_FAST
3599 i = G.count_SIGCHLD;
3600#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003601 childpid = waitpid(-1, &status, attributes);
3602 if (childpid <= 0) {
3603 if (childpid && errno != ECHILD)
3604 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003605#if ENABLE_HUSH_FAST
3606 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003607 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003608 G.handled_SIGCHLD = i;
3609//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3610 }
3611#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003612 break;
3613 }
3614 dead = WIFEXITED(status) || WIFSIGNALED(status);
3615
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003616#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003617 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003618 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003619 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3620 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003621 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003622 childpid, WTERMSIG(status), WEXITSTATUS(status));
3623 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003624 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003625 childpid, WEXITSTATUS(status));
3626#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003627 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003628 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003629 for (i = 0; i < fg_pipe->num_cmds; i++) {
3630 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3631 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003632 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003633 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003634 fg_pipe->cmds[i].pid = 0;
3635 fg_pipe->alive_cmds--;
3636 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003637 /* last process gives overall exitstatus */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003638 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003639 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003640 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003641 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00003642 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003643 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003644 */
3645 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003646 int sig = WTERMSIG(status);
3647 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denis Vlasenko40e84372009-04-18 11:23:38 +00003648 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003649 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003650 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003651 fg_pipe->cmds[i].is_stopped = 1;
3652 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003653 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003654 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3655 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3656 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003657 /* All processes in fg pipe have exited or stopped */
3658/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3659 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3660 * and "killall -STOP cat" */
3661 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003662#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003663 if (fg_pipe->alive_cmds)
3664 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003665#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003666 return rcode;
3667 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02003668 if (!fg_pipe->alive_cmds)
3669 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003670 }
3671 /* There are still running processes in the fg pipe */
3672 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003673 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003674 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003675 }
3676
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003677#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003678 /* We asked to wait for bg or orphaned children */
3679 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003680 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003681 for (i = 0; i < pi->num_cmds; i++) {
3682 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003683 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003684 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003685 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003686 /* Happens when shell is used as init process (init=/bin/sh) */
3687 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003688 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003689
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003690 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003691 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003692 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003693 pi->cmds[i].pid = 0;
3694 pi->alive_cmds--;
3695 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003696 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003697 printf(JOB_STATUS_FORMAT, pi->jobid,
3698 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003699 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003700 }
3701 } else {
3702 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003703 pi->cmds[i].is_stopped = 1;
3704 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003705 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003706#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003707 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003708
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003709 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003710}
3711
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003712#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003713static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3714{
3715 pid_t p;
3716 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04003717 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003718 /* Job finished, move the shell to the foreground */
3719 p = getpgrp(); /* our process group id */
3720 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3721 tcsetpgrp(G_interactive_fd, p);
3722 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00003723 return rcode;
3724}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003725#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003726
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003727/* Start all the jobs, but don't wait for anything to finish.
3728 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003729 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003730 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003731 * to finish to determine the exit status of the pipe. If the pipe
3732 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003733 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003734 * return value.
3735 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003736 * Returns -1 only if started some children. IOW: we have to
3737 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003738 *
3739 * The only case when we do not need to [v]fork is when the pipe
3740 * is single, non-backgrounded, non-subshell command. Examples:
3741 * cmd ; ... { list } ; ...
3742 * cmd && ... { list } && ...
3743 * cmd || ... { list } || ...
3744 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3745 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003746 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00003747 *
3748 * Cases when we must fork:
3749 * non-single: cmd | cmd
3750 * backgrounded: cmd & { list } &
3751 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00003752 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003753static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003754{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003755 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003756 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003757 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003758 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003759 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003760 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003761 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003762 /* it is not always needed, but we aim to smaller code */
3763 int squirrel[] = { -1, -1, -1 };
3764 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003765
Denis Vlasenko552433b2009-04-04 19:29:21 +00003766 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003767 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003768
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003769 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003770 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003771 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003772 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003773
Denis Vlasenko552433b2009-04-04 19:29:21 +00003774 if (pi->num_cmds != 1
3775 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003776 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00003777 ) {
3778 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003779 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003780
Denis Vlasenko552433b2009-04-04 19:29:21 +00003781 pi->alive_cmds = 1;
3782
3783 debug_printf_exec(": group:%p argv:'%s'\n",
3784 command->group, command->argv ? command->argv[0] : "NONE");
3785
3786 if (command->group) {
3787#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003788 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003789 /* "executing" func () { list } */
3790 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003791
Denis Vlasenkobc569742009-04-12 20:35:19 +00003792 funcp = new_function(command->argv[0]);
3793 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003794 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003795# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003796 funcp->body_as_string = command->group_as_string;
3797 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003798# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003799 command->group = NULL;
3800 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00003801 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3802 funcp->parent_cmd = command;
3803 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003804
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003805 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3806 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00003807 return EXIT_SUCCESS;
3808 }
3809#endif
3810 /* { list } */
3811 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003812 rcode = 1; /* exitcode if redir failed */
3813 if (setup_redirects(command, squirrel) == 0) {
3814 debug_printf_exec(": run_list\n");
3815 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003816 }
Eric Andersen04407e52001-06-07 16:42:05 +00003817 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003818 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003819 debug_leave();
3820 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003821 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003822 }
3823
Denis Vlasenko552433b2009-04-04 19:29:21 +00003824 argv = command->argv ? command->argv : (char **) &null_ptr;
3825 {
3826 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003827#if ENABLE_HUSH_FUNCTIONS
3828 const struct function *funcp;
3829#else
3830 enum { funcp = 0 };
3831#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003832 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003833 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003834
Denis Vlasenko552433b2009-04-04 19:29:21 +00003835 if (argv[command->assignment_cnt] == NULL) {
3836 /* Assignments, but no command */
3837 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003838 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003839 restore_redirects(squirrel);
3840 /* Set shell variables */
3841 while (*argv) {
3842 p = expand_string_to_string(*argv);
3843 debug_printf_exec("set shell var:'%s'->'%s'\n",
3844 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003845 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003846 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00003847 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00003848 /* Do we need to flag set_local_var() errors?
3849 * "assignment to readonly var" and "putenv error"
3850 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003851 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003852 debug_leave();
3853 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003854 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00003855 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003856
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003857 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003858 if (0) {}
3859#if ENABLE_HUSH_BASH_COMPAT
3860 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003861 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3862 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003863#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003864#ifdef CMD_SINGLEWORD_NOGLOB_COND
3865 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3866 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3867
3868 }
3869#endif
3870 else {
3871 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3872 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003873
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003874 x = find_builtin(argv_expanded[0]);
3875#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003876 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003877 if (!x)
3878 funcp = find_function(argv_expanded[0]);
3879#endif
3880 if (x || funcp) {
3881 if (!funcp) {
3882 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3883 debug_printf("exec with redirects only\n");
3884 rcode = setup_redirects(command, NULL);
3885 goto clean_up_and_ret1;
3886 }
Eric Andersen25f27032001-04-26 23:22:31 +00003887 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003888 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003889 * This is perfect for work that comes after exec().
3890 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003891 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003892 rcode = setup_redirects(command, squirrel);
3893 if (rcode == 0) {
3894 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003895 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003896 if (!funcp) {
3897 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003898 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003899 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003900 fflush(NULL);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003901 }
3902#if ENABLE_HUSH_FUNCTIONS
3903 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02003904# if ENABLE_HUSH_LOCAL
3905 struct variable **sv;
3906 sv = G.shadowed_vars_pp;
3907 G.shadowed_vars_pp = &old_vars;
3908# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003909 debug_printf_exec(": function '%s' '%s'...\n",
3910 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003911 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003912# if ENABLE_HUSH_LOCAL
3913 G.shadowed_vars_pp = sv;
3914# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003915 }
3916#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003917 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003918#if ENABLE_FEATURE_SH_STANDALONE
3919 clean_up_and_ret:
3920#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003921 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003922 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003923 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003924 clean_up_and_ret1:
3925 free(argv_expanded);
3926 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003927 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003928 debug_printf_exec("run_pipe return %d\n", rcode);
3929 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003930 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003931
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003932#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003933 i = find_applet_by_name(argv_expanded[0]);
3934 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003935 rcode = setup_redirects(command, squirrel);
3936 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003937 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003938 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003939 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003940 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003941 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003942 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003943 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003944 }
3945#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00003946 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00003947 }
3948
Denis Vlasenko552433b2009-04-04 19:29:21 +00003949 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003950 /* NB: argv_expanded may already be created, and that
3951 * might include `cmd` runs! Do not rerun it! We *must*
3952 * use argv_expanded if it's non-NULL */
3953
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003954 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003955 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003956 nextin = 0;
3957
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003958 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003959 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003960#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003961 volatile nommu_save_t nommu_save;
3962 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003963 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003964 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003965 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003966#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003967 command = &(pi->cmds[i]);
3968 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003969 debug_printf_exec(": pipe member '%s' '%s'...\n",
3970 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003971 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003972 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00003973 }
Eric Andersen25f27032001-04-26 23:22:31 +00003974
3975 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003976 pipefds.rd = 0;
3977 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003978 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003979 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00003980
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003981 command->pid = BB_MMU ? fork() : vfork();
3982 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003983#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003984 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkod5762932009-03-31 11:22:57 +00003985
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003986 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00003987 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003988 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00003989 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003990 pgrp = pi->pgrp;
3991 if (pgrp < 0) /* true for 1st process only */
3992 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003993 if (setpgid(0, pgrp) == 0
3994 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04003995 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003996 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003997 /* We do it in *every* child, not just first,
3998 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003999 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004000 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004001 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004002#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004003 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4004 /* 1st cmd in backgrounded pipe
4005 * should have its stdin /dev/null'ed */
4006 close(0);
4007 if (open(bb_dev_null, O_RDONLY))
4008 xopen("/", O_RDONLY);
4009 } else {
4010 xmove_fd(nextin, 0);
4011 }
4012 xmove_fd(pipefds.wr, 1);
4013 if (pipefds.rd > 1)
4014 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004015 /* Like bash, explicit redirects override pipes,
4016 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004017 if (setup_redirects(command, NULL))
4018 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004019
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004020 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004021 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4022
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004023 /* Stores to nommu_save list of env vars putenv'ed
4024 * (NOMMU, on MMU we don't need that) */
4025 /* cast away volatility... */
4026 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004027 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004028 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004029
Denis Vlasenkof9375282009-04-05 19:13:39 +00004030 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004031#if ENABLE_HUSH_FAST
4032 G.count_SIGCHLD++;
4033//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4034#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004035 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004036#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004037 /* Clean up after vforked child */
4038 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004039 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004040 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004041 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004042#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004043 free(argv_expanded);
4044 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004045 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004046 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00004047 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004048 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004049 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004050#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004051 /* Second and next children need to know pid of first one */
4052 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004053 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004054#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004055 }
Eric Andersen25f27032001-04-26 23:22:31 +00004056
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004057 if (i)
4058 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004059 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004060 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004061 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004062 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004063 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004064
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004065 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004066 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004067 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4068 return 1;
4069 }
4070
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004071 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004072 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004073 return -1;
4074}
4075
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004076#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004077static void debug_print_tree(struct pipe *pi, int lvl)
4078{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004079 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004080 [PIPE_SEQ] = "SEQ",
4081 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004082 [PIPE_OR ] = "OR" ,
4083 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004084 };
4085 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004086 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00004087#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004088 [RES_IF ] = "IF" ,
4089 [RES_THEN ] = "THEN" ,
4090 [RES_ELIF ] = "ELIF" ,
4091 [RES_ELSE ] = "ELSE" ,
4092 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00004093#endif
4094#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004095 [RES_FOR ] = "FOR" ,
4096 [RES_WHILE] = "WHILE",
4097 [RES_UNTIL] = "UNTIL",
4098 [RES_DO ] = "DO" ,
4099 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004100#endif
4101#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004102 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00004103#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004104#if ENABLE_HUSH_CASE
4105 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004106 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004107 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004108 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004109 [RES_ESAC ] = "ESAC" ,
4110#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004111 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004112 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004113 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004114 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004115 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004116 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004117 "[noglob]",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004118#if ENABLE_HUSH_FUNCTIONS
4119 "func()",
4120#endif
4121 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004122
4123 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004124
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004125 pin = 0;
4126 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004127 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4128 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004129 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004130 while (prn < pi->num_cmds) {
4131 struct command *command = &pi->cmds[prn];
4132 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004133
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004134 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004135 lvl*2, "", prn,
4136 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004137 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004138 fprintf(stderr, " group %s: (argv=%p)\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004139 CMDTYPE[command->cmd_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004140 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004141 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004142 prn++;
4143 continue;
4144 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004145 if (argv) while (*argv) {
4146 fprintf(stderr, " '%s'", *argv);
4147 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004148 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004149 fprintf(stderr, "\n");
4150 prn++;
4151 }
4152 pi = pi->next;
4153 pin++;
4154 }
4155}
4156#endif
4157
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004158/* NB: called by pseudo_exec, and therefore must not modify any
4159 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004160static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004161{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004162#if ENABLE_HUSH_CASE
4163 char *case_word = NULL;
4164#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004165#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004166 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004167 char **for_lcur = NULL;
4168 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004169#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004170 smallint last_followup;
4171 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004172#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004173 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004174#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004175 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004176#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004177#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004178 smallint rword; /* enum reserved_style */
4179 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004180#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004181
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004182 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004183 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004184
Denis Vlasenko06810332007-05-21 23:30:54 +00004185#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004186 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004187 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4188 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004189 continue;
4190 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004191 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004192 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004193 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004194 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004195 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004196 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004197 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004198 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004199 continue;
4200 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004201 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4202 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004203 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004204 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004205 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004206 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004207 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004208 }
4209 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004210#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004211
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004212 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004213 * in order to return, no direct "return" statements please.
4214 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004215
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004216#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004217 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004218#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004219
Denis Vlasenko0e151382009-04-06 18:40:31 +00004220#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004221 rword = RES_NONE;
4222 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004223#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004224 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004225 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004226
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004227 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004228 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004229 if (G.flag_SIGINT)
4230 break;
4231
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004232 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004233 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4234 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004235#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004236 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004237 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004238 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004239 /* start of a loop: remember where loop starts */
4240 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004241 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004242 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004243#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004244 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004245 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004246 if ((rcode == 0 && last_followup == PIPE_OR)
4247 || (rcode != 0 && last_followup == PIPE_AND)
4248 ) {
4249 /* It is "<true> || CMD" or "<false> && CMD"
4250 * and we should not execute CMD */
4251 debug_printf_exec("skipped cmd because of || or &&\n");
4252 last_followup = pi->followup;
4253 continue;
4254 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004255 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004256 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004257 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004258#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004259 if (cond_code) {
4260 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004261 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004262 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004263 /* "if <false> THEN cmd": skip cmd */
4264 continue;
4265 }
4266 } else {
4267 if (rword == RES_ELSE || rword == RES_ELIF) {
4268 /* "if <true> then ... ELSE/ELIF cmd":
4269 * skip cmd and all following ones */
4270 break;
4271 }
4272 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004273#endif
4274#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004275 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004276 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004277 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004278
4279 static const char encoded_dollar_at[] ALIGN1 = {
4280 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4281 }; /* encoded representation of "$@" */
4282 static const char *const encoded_dollar_at_argv[] = {
4283 encoded_dollar_at, NULL
4284 }; /* argv list with one element: "$@" */
4285 char **vals;
4286
4287 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004288 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004289 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004290 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004291 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004292 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004293 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004294 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004295 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004296 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004297 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004298 debug_print_strings("for_list made from", vals);
4299 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004300 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004301 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004302 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004303 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004304 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004305 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004306 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004307 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004308 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004309 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004310 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004311 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004312 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 +02004313 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004314 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004315 if (rword == RES_IN) {
4316 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4317 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004318 if (rword == RES_DONE) {
4319 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004320 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004321#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004322#if ENABLE_HUSH_CASE
4323 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004324 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004325 continue;
4326 }
4327 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004328 char **argv;
4329
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004330 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4331 break;
4332 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004333 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004334 while (*argv) {
4335 char *pattern = expand_string_to_string(*argv);
4336 /* TODO: which FNM_xxx flags to use? */
4337 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4338 free(pattern);
4339 if (cond_code == 0) { /* match! we will execute this branch */
4340 free(case_word); /* make future "word)" stop */
4341 case_word = NULL;
4342 break;
4343 }
4344 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004345 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004346 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004347 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004348 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004349 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004350 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004351 }
4352#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004353 /* Just pressing <enter> in shell should check for jobs.
4354 * OTOH, in non-interactive shell this is useless
4355 * and only leads to extra job checks */
4356 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004357 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004358 goto check_jobs_and_continue;
4359 continue;
4360 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004361
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004362 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004363 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004364 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004365 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004366 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004367 {
4368 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004369#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004370 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004371#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004372 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4373 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004374 /* We ran a builtin, function, or group.
4375 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004376 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004377 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004378 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004379 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004380#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004381 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004382 if (G.flag_break_continue) {
4383 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004384 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004385 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004386 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004387 G.depth_break_continue--;
4388 if (G.depth_break_continue == 0)
4389 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004390 /* else: e.g. "continue 2" should *break* once, *then* continue */
4391 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004392 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004393 goto check_jobs_and_break;
4394 /* "continue": simulate end of loop */
4395 rword = RES_DONE;
4396 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004397 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004398#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004399#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004400 if (G.flag_return_in_progress == 1) {
4401 /* same as "goto check_jobs_and_break" */
4402 checkjobs(NULL);
4403 break;
4404 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004405#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004406 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004407 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004408 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004409 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4410 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004411 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004412#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004413 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004414 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004415#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004416 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004417 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004418 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004419#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004420 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004421 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004422 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004423 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004424 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004425 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004426#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004427 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004428 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004429 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004430 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004431 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004432 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004433 }
4434 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004435
4436 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004437#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004438 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004439 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004440#endif
4441#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004442 /* Beware of "while false; true; do ..."! */
4443 if (pi->next && pi->next->res_word == RES_DO) {
4444 if (rword == RES_WHILE) {
4445 if (rcode) {
4446 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004447 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004448 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4449 goto check_jobs_and_break;
4450 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004451 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004452 if (rword == RES_UNTIL) {
4453 if (!rcode) {
4454 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004455 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004456 checkjobs(NULL);
4457 break;
4458 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004459 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004460 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004461#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004462
4463 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004464 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004465 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004466
4467#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004468 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004469#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004470#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004471 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004472 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004473 free(for_list);
4474#endif
4475#if ENABLE_HUSH_CASE
4476 free(case_word);
4477#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004478 debug_leave();
4479 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004480 return rcode;
4481}
4482
Eric Andersen25f27032001-04-26 23:22:31 +00004483/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004484static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004485{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004486 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004487 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004488 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004489 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004490 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004491 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004492 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004493 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004494 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004495 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004496 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004497 return rcode;
4498}
4499
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004500
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004501static struct pipe *new_pipe(void)
4502{
Eric Andersen25f27032001-04-26 23:22:31 +00004503 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004504 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004505 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004506 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004507 return pi;
4508}
4509
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004510/* Command (member of a pipe) is complete, or we start a new pipe
4511 * if ctx->command is NULL.
4512 * No errors possible here.
4513 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004514static int done_command(struct parse_context *ctx)
4515{
4516 /* The command is really already in the pipe structure, so
4517 * advance the pipe counter and make a new, null command. */
4518 struct pipe *pi = ctx->pipe;
4519 struct command *command = ctx->command;
4520
4521 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004522 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004523 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004524 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004525 }
4526 pi->num_cmds++;
4527 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004528 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004529 } else {
4530 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4531 }
4532
4533 /* Only real trickiness here is that the uncommitted
4534 * command structure is not counted in pi->num_cmds. */
4535 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004536 ctx->command = command = &pi->cmds[pi->num_cmds];
4537 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004538 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004539 return pi->num_cmds; /* used only for 0/nonzero check */
4540}
4541
4542static void done_pipe(struct parse_context *ctx, pipe_style type)
4543{
4544 int not_null;
4545
4546 debug_printf_parse("done_pipe entered, followup %d\n", type);
4547 /* Close previous command */
4548 not_null = done_command(ctx);
4549 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004550#if HAS_KEYWORDS
4551 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4552 ctx->ctx_inverted = 0;
4553 ctx->pipe->res_word = ctx->ctx_res_w;
4554#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004555
4556 /* Without this check, even just <enter> on command line generates
4557 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004558 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004559 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004560#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004561 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004562#endif
4563#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004564 || ctx->ctx_res_w == RES_DONE
4565 || ctx->ctx_res_w == RES_FOR
4566 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004567#endif
4568#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004569 || ctx->ctx_res_w == RES_ESAC
4570#endif
4571 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004572 struct pipe *new_p;
4573 debug_printf_parse("done_pipe: adding new pipe: "
4574 "not_null:%d ctx->ctx_res_w:%d\n",
4575 not_null, ctx->ctx_res_w);
4576 new_p = new_pipe();
4577 ctx->pipe->next = new_p;
4578 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004579 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004580 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004581 * This is used to control execution.
4582 * RES_FOR and RES_IN are NOT sticky (needed to support
4583 * cases where variable or value happens to match a keyword):
4584 */
4585#if ENABLE_HUSH_LOOPS
4586 if (ctx->ctx_res_w == RES_FOR
4587 || ctx->ctx_res_w == RES_IN)
4588 ctx->ctx_res_w = RES_NONE;
4589#endif
4590#if ENABLE_HUSH_CASE
4591 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004592 ctx->ctx_res_w = RES_CASE_BODY;
4593 if (ctx->ctx_res_w == RES_CASE)
4594 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004595#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004596 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004597 /* Create the memory for command, roughly:
4598 * ctx->pipe->cmds = new struct command;
4599 * ctx->command = &ctx->pipe->cmds[0];
4600 */
4601 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004602 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004603 }
4604 debug_printf_parse("done_pipe return\n");
4605}
4606
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004607static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004608{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004609 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004610 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004611 /* Create the memory for command, roughly:
4612 * ctx->pipe->cmds = new struct command;
4613 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004614 */
4615 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004616}
4617
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004618/* If a reserved word is found and processed, parse context is modified
4619 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004620 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004621#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004622struct reserved_combo {
4623 char literal[6];
4624 unsigned char res;
4625 unsigned char assignment_flag;
4626 int flag;
4627};
4628enum {
4629 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004630#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004631 FLAG_IF = (1 << RES_IF ),
4632 FLAG_THEN = (1 << RES_THEN ),
4633 FLAG_ELIF = (1 << RES_ELIF ),
4634 FLAG_ELSE = (1 << RES_ELSE ),
4635 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004636#endif
4637#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004638 FLAG_FOR = (1 << RES_FOR ),
4639 FLAG_WHILE = (1 << RES_WHILE),
4640 FLAG_UNTIL = (1 << RES_UNTIL),
4641 FLAG_DO = (1 << RES_DO ),
4642 FLAG_DONE = (1 << RES_DONE ),
4643 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004644#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004645#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004646 FLAG_MATCH = (1 << RES_MATCH),
4647 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004648#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004649 FLAG_START = (1 << RES_XXXX ),
4650};
4651
4652static const struct reserved_combo* match_reserved_word(o_string *word)
4653{
Eric Andersen25f27032001-04-26 23:22:31 +00004654 /* Mostly a list of accepted follow-up reserved words.
4655 * FLAG_END means we are done with the sequence, and are ready
4656 * to turn the compound list into a command.
4657 * FLAG_START means the word must start a new compound list.
4658 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004659 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00004660#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004661 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4662 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4663 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4664 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4665 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4666 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004667#endif
4668#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004669 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4670 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4671 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4672 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4673 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4674 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004675#endif
4676#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004677 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4678 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004679#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004680 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004681 const struct reserved_combo *r;
4682
4683 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4684 if (strcmp(word->data, r->literal) == 0)
4685 return r;
4686 }
4687 return NULL;
4688}
Denis Vlasenkobb929512009-04-16 10:59:40 +00004689/* Return 0: not a keyword, 1: keyword
4690 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004691static int reserved_word(o_string *word, struct parse_context *ctx)
4692{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004693#if ENABLE_HUSH_CASE
4694 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004695 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004696 };
4697#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004698 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004699
Denis Vlasenkobb929512009-04-16 10:59:40 +00004700 if (word->o_quoted)
4701 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004702 r = match_reserved_word(word);
4703 if (!r)
4704 return 0;
4705
4706 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004707#if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004708 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4709 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004710 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004711 } else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004712#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004713 if (r->flag == 0) { /* '!' */
4714 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004715 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004716 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004717 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004718 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004719 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004720 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004721 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004722 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004723
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004724 old = xmalloc(sizeof(*old));
4725 debug_printf_parse("push stack %p\n", old);
4726 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004727 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004728 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004729 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004730 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004731 ctx->ctx_res_w = RES_SNTX;
4732 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004733 } else {
4734 /* "{...} fi" is ok. "{...} if" is not
4735 * Example:
4736 * if { echo foo; } then { echo bar; } fi */
4737 if (ctx->command->group)
4738 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004739 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004740
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004741 ctx->ctx_res_w = r->res;
4742 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004743 word->o_assignment = r->assignment_flag;
4744
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004745 if (ctx->old_flag & FLAG_END) {
4746 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004747
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004748 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004749 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004750 old = ctx->stack;
4751 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004752 old->command->cmd_type = CMD_NORMAL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004753#if !BB_MMU
4754 o_addstr(&old->as_string, ctx->as_string.data);
4755 o_free_unsafe(&ctx->as_string);
4756 old->command->group_as_string = xstrdup(old->as_string.data);
4757 debug_printf_parse("pop, remembering as:'%s'\n",
4758 old->command->group_as_string);
4759#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004760 *ctx = *old; /* physical copy */
4761 free(old);
4762 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004763 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004764}
Denis Vlasenko06810332007-05-21 23:30:54 +00004765#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004766
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004767/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004768 * Normal return is 0. Syntax errors return 1.
4769 * Note: on return, word is reset, but not o_free'd!
4770 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004771static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004772{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004773 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004774
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004775 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004776 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004777 debug_printf_parse("done_word return 0: true null, ignored\n");
4778 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004779 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004780
Eric Andersen25f27032001-04-26 23:22:31 +00004781 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004782 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4783 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004784 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4785 * "2.7 Redirection
4786 * ...the word that follows the redirection operator
4787 * shall be subjected to tilde expansion, parameter expansion,
4788 * command substitution, arithmetic expansion, and quote
4789 * removal. Pathname expansion shall not be performed
4790 * on the word by a non-interactive shell; an interactive
4791 * shell may perform it, but shall do so only when
4792 * the expansion would result in one word."
4793 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004794 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004795 /* Cater for >\file case:
4796 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4797 * Same with heredocs:
4798 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4799 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004800 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4801 unbackslash(ctx->pending_redirect->rd_filename);
4802 /* Is it <<"HEREDOC"? */
4803 if (word->o_quoted) {
4804 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4805 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004806 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004807 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004808 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004809 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004810 /* If this word wasn't an assignment, next ones definitely
4811 * can't be assignments. Even if they look like ones. */
4812 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4813 && word->o_assignment != WORD_IS_KEYWORD
4814 ) {
4815 word->o_assignment = NOT_ASSIGNMENT;
4816 } else {
4817 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4818 command->assignment_cnt++;
4819 word->o_assignment = MAYBE_ASSIGNMENT;
4820 }
4821
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004822#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004823# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004824 if (ctx->ctx_dsemicolon
4825 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4826 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004827 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004828 /* ctx->ctx_res_w = RES_MATCH; */
4829 ctx->ctx_dsemicolon = 0;
4830 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004831# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004832 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004833# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004834 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4835 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004836# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004837# if ENABLE_HUSH_CASE
4838 && ctx->ctx_res_w != RES_CASE
4839# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004840 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004841 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004842 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004843 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004844 debug_printf_parse("done_word return %d\n",
4845 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004846 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004847 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004848# ifdef CMD_SINGLEWORD_NOGLOB_COND
4849 if (strcmp(word->data, "export") == 0
4850# if ENABLE_HUSH_LOCAL
4851 || strcmp(word->data, "local") == 0
4852# endif
4853 ) {
4854 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4855 } else
4856# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004857# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004858 if (strcmp(word->data, "[[") == 0) {
4859 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4860 }
4861 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004862# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004863 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004864#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00004865 if (command->group) {
4866 /* "{ echo foo; } echo bar" - bad */
4867 syntax_error_at(word->data);
4868 debug_printf_parse("done_word return 1: syntax error, "
4869 "groups and arglists don't mix\n");
4870 return 1;
4871 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004872 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004873 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4874 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004875 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004876 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004877 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004878 char *p = word->data;
4879 while (p[0] == SPECIAL_VAR_SYMBOL
4880 && (p[1] & 0x7f) == '@'
4881 && p[2] == SPECIAL_VAR_SYMBOL
4882 ) {
4883 p += 3;
4884 }
4885 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004886 /* saw no "$@", or not only "$@" but some
4887 * real text is there too */
4888 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004889 * e.g. "", $empty"" etc to not disappear */
4890 o_addchr(word, SPECIAL_VAR_SYMBOL);
4891 o_addchr(word, SPECIAL_VAR_SYMBOL);
4892 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004893 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004894 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004895 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004896 }
Eric Andersen25f27032001-04-26 23:22:31 +00004897
Denis Vlasenko06810332007-05-21 23:30:54 +00004898#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004899 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004900 if (word->o_quoted
4901 || !is_well_formed_var_name(command->argv[0], '\0')
4902 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004903 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004904 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004905 return 1;
4906 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004907 /* Force FOR to have just one word (variable name) */
4908 /* NB: basically, this makes hush see "for v in ..."
4909 * syntax as if it is "for v; in ...". FOR and IN become
4910 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004911 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004912 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004913#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004914#if ENABLE_HUSH_CASE
4915 /* Force CASE to have just one word */
4916 if (ctx->ctx_res_w == RES_CASE) {
4917 done_pipe(ctx, PIPE_SEQ);
4918 }
4919#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004920
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004921 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004922
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004923 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004924 return 0;
4925}
4926
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004927
4928/* Peek ahead in the input to find out if we have a "&n" construct,
4929 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004930 * Return:
4931 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4932 * REDIRFD_SYNTAX_ERR if syntax error,
4933 * REDIRFD_TO_FILE if no & was seen,
4934 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004935 */
4936#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004937#define parse_redir_right_fd(as_string, input) \
4938 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004939#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004940static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004941{
4942 int ch, d, ok;
4943
4944 ch = i_peek(input);
4945 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004946 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004947
4948 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004949 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004950 ch = i_peek(input);
4951 if (ch == '-') {
4952 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004953 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004954 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004955 }
4956 d = 0;
4957 ok = 0;
4958 while (ch != EOF && isdigit(ch)) {
4959 d = d*10 + (ch-'0');
4960 ok = 1;
4961 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004962 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004963 ch = i_peek(input);
4964 }
4965 if (ok) return d;
4966
4967//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4968
4969 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004970 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004971}
4972
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004973/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004974 */
4975static int parse_redirect(struct parse_context *ctx,
4976 int fd,
4977 redir_type style,
4978 struct in_str *input)
4979{
4980 struct command *command = ctx->command;
4981 struct redir_struct *redir;
4982 struct redir_struct **redirp;
4983 int dup_num;
4984
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004985 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004986 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004987 /* Check for a '>&1' type redirect */
4988 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4989 if (dup_num == REDIRFD_SYNTAX_ERR)
4990 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004991 } else {
4992 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004993 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004994 if (dup_num) { /* <<-... */
4995 ch = i_getch(input);
4996 nommu_addchr(&ctx->as_string, ch);
4997 ch = i_peek(input);
4998 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004999 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005000
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005001 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005002 int ch = i_peek(input);
5003 if (ch == '|') {
5004 /* >|FILE redirect ("clobbering" >).
5005 * Since we do not support "set -o noclobber" yet,
5006 * >| and > are the same for now. Just eat |.
5007 */
5008 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005009 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005010 }
5011 }
5012
5013 /* Create a new redir_struct and append it to the linked list */
5014 redirp = &command->redirects;
5015 while ((redir = *redirp) != NULL) {
5016 redirp = &(redir->next);
5017 }
5018 *redirp = redir = xzalloc(sizeof(*redir));
5019 /* redir->next = NULL; */
5020 /* redir->rd_filename = NULL; */
5021 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005022 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005023
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005024 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5025 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005026
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005027 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005028 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005029 /* Erik had a check here that the file descriptor in question
5030 * is legit; I postpone that to "run time"
5031 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005032 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5033 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005034 } else {
5035 /* Set ctx->pending_redirect, so we know what to do at the
5036 * end of the next parsed word. */
5037 ctx->pending_redirect = redir;
5038 }
5039 return 0;
5040}
5041
Eric Andersen25f27032001-04-26 23:22:31 +00005042/* If a redirect is immediately preceded by a number, that number is
5043 * supposed to tell which file descriptor to redirect. This routine
5044 * looks for such preceding numbers. In an ideal world this routine
5045 * needs to handle all the following classes of redirects...
5046 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5047 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5048 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5049 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005050 *
5051 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5052 * "2.7 Redirection
5053 * ... If n is quoted, the number shall not be recognized as part of
5054 * the redirection expression. For example:
5055 * echo \2>a
5056 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005057 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005058 *
5059 * A -1 return means no valid number was found,
5060 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005061 */
5062static int redirect_opt_num(o_string *o)
5063{
5064 int num;
5065
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005066 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005067 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005068 num = bb_strtou(o->data, NULL, 10);
5069 if (errno || num < 0)
5070 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005071 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005072 return num;
5073}
5074
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005075#if BB_MMU
5076#define fetch_till_str(as_string, input, word, skip_tabs) \
5077 fetch_till_str(input, word, skip_tabs)
5078#endif
5079static char *fetch_till_str(o_string *as_string,
5080 struct in_str *input,
5081 const char *word,
5082 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005083{
5084 o_string heredoc = NULL_O_STRING;
5085 int past_EOL = 0;
5086 int ch;
5087
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005088 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005089 while (1) {
5090 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005091 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005092 if (ch == '\n') {
5093 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5094 heredoc.data[past_EOL] = '\0';
5095 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5096 return heredoc.data;
5097 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005098 do {
5099 o_addchr(&heredoc, ch);
5100 past_EOL = heredoc.length;
5101 jump_in:
5102 do {
5103 ch = i_getch(input);
5104 nommu_addchr(as_string, ch);
5105 } while (skip_tabs && ch == '\t');
5106 } while (ch == '\n');
5107 }
5108 if (ch == EOF) {
5109 o_free_unsafe(&heredoc);
5110 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005111 }
5112 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005113 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005114 }
5115}
5116
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005117/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5118 * and load them all. There should be exactly heredoc_cnt of them.
5119 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005120static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5121{
5122 struct pipe *pi = ctx->list_head;
5123
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005124 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005125 int i;
5126 struct command *cmd = pi->cmds;
5127
5128 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5129 pi->num_cmds,
5130 cmd->argv ? cmd->argv[0] : "NONE");
5131 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005132 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005133
5134 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5135 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005136 while (redir) {
5137 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005138 char *p;
5139
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005140 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005141 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005142 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005143 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005144 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005145 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005146 return 1;
5147 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005148 free(redir->rd_filename);
5149 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005150 heredoc_cnt--;
5151 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005152 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005153 }
5154 cmd++;
5155 }
5156 pi = pi->next;
5157 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005158#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005159 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005160 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005161 bb_error_msg_and_die("heredoc BUG 2");
5162#endif
5163 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005164}
5165
5166
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005167#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005168static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005169{
5170 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00005171 int pid, channel[2];
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005172#if !BB_MMU
5173 char **to_free;
5174#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005175
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005176 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00005177 pid = BB_MMU ? fork() : vfork();
5178 if (pid < 0)
5179 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005180
Denis Vlasenko05743d72008-02-10 12:10:08 +00005181 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005182 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005183 /* Process substitution is not considered to be usual
5184 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005185 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5186 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005187 bb_signals(0
5188 + (1 << SIGTSTP)
5189 + (1 << SIGTTIN)
5190 + (1 << SIGTTOU)
5191 , SIG_IGN);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005192 close(channel[0]); /* NB: close _first_, then move fd! */
5193 xmove_fd(channel[1], 1);
5194 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005195 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005196 /* Awful hack for `trap` or $(trap).
5197 *
5198 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5199 * contains an example where "trap" is executed in a subshell:
5200 *
5201 * save_traps=$(trap)
5202 * ...
5203 * eval "$save_traps"
5204 *
5205 * Standard does not say that "trap" in subshell shall print
5206 * parent shell's traps. It only says that its output
5207 * must have suitable form, but then, in the above example
5208 * (which is not supposed to be normative), it implies that.
5209 *
5210 * bash (and probably other shell) does implement it
5211 * (traps are reset to defaults, but "trap" still shows them),
5212 * but as a result, "trap" logic is hopelessly messed up:
5213 *
5214 * # trap
5215 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5216 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5217 * # true | trap <--- trap is in subshell - no output (ditto)
5218 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5219 * trap -- 'echo Ho' SIGWINCH
5220 * # echo `(trap)` <--- in subshell in subshell - output
5221 * trap -- 'echo Ho' SIGWINCH
5222 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5223 * trap -- 'echo Ho' SIGWINCH
5224 *
5225 * The rules when to forget and when to not forget traps
5226 * get really complex and nonsensical.
5227 *
5228 * Our solution: ONLY bare $(trap) or `trap` is special.
5229 */
5230 s = skip_whitespace(s);
5231 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5232 {
5233 static const char *const argv[] = { NULL, NULL };
5234 builtin_trap((char**)argv);
5235 exit(0); /* not _exit() - we need to fflush */
5236 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005237#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005238 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005239 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005240 _exit(G.last_exitcode);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005241#else
5242 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005243 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5244 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005245 * echo OK
5246 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005247 re_execute_shell(&to_free,
5248 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005249 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005250 G.global_argv + 1,
5251 NULL);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005252#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005253 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005254
5255 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005256#if ENABLE_HUSH_FAST
5257 G.count_SIGCHLD++;
5258//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);
5259#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005260 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005261#if !BB_MMU
5262 free(to_free);
5263#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005264 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00005265 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00005266 return pf;
5267}
5268
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005269/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005270static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005271{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005272 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00005273 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005274 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005275
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005276 pf = generate_stream_from_string(s);
5277 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00005278 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005279 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00005280
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005281 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005282 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005283 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005284 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005285 if (ch == '\n') {
5286 eol_cnt++;
5287 continue;
5288 }
5289 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005290 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005291 eol_cnt--;
5292 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005293 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005294 }
5295
5296 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005297 /* Note: we got EOF, and we just close the read end of the pipe.
5298 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005299 * Try these:
5300 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5301 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005302 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005303 fclose(pf);
5304 debug_printf("closed FILE from child. return 0\n");
5305 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005306}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005307#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005308
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005309static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005310 struct in_str *input, int ch)
5311{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005312 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005313 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005314 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005315 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005316 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005317 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005318
5319 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005320#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005321 if (ch == '(' && !dest->o_quoted) {
5322 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005323 if (done_word(dest, ctx))
5324 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005325 if (!command->argv)
5326 goto skip; /* (... */
5327 if (command->argv[1]) { /* word word ... (... */
5328 syntax_error_unexpected_ch('(');
5329 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005330 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005331 /* it is "word(..." or "word (..." */
5332 do
5333 ch = i_getch(input);
5334 while (ch == ' ' || ch == '\t');
5335 if (ch != ')') {
5336 syntax_error_unexpected_ch(ch);
5337 return 1;
5338 }
5339 nommu_addchr(&ctx->as_string, ch);
5340 do
5341 ch = i_getch(input);
5342 while (ch == ' ' || ch == '\t' || ch == '\n');
5343 if (ch != '{') {
5344 syntax_error_unexpected_ch(ch);
5345 return 1;
5346 }
5347 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005348 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005349 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005350 }
5351#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005352 if (command->argv /* word [word]{... */
5353 || dest->length /* word{... */
5354 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005355 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005356 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005357 debug_printf_parse("parse_group return 1: "
5358 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005359 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005360 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005361
5362#if ENABLE_HUSH_FUNCTIONS
5363 skip:
5364#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005365 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005366 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005367 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005368 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005369 } else {
5370 /* bash does not allow "{echo...", requires whitespace */
5371 ch = i_getch(input);
5372 if (ch != ' ' && ch != '\t' && ch != '\n') {
5373 syntax_error_unexpected_ch(ch);
5374 return 1;
5375 }
5376 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005377 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005378
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005379 {
5380#if !BB_MMU
5381 char *as_string = NULL;
5382#endif
5383 pipe_list = parse_stream(&as_string, input, endch);
5384#if !BB_MMU
5385 if (as_string)
5386 o_addstr(&ctx->as_string, as_string);
5387#endif
5388 /* empty ()/{} or parse error? */
5389 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005390 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005391#if !BB_MMU
5392 free(as_string);
5393#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005394 debug_printf_parse("parse_group return 1: "
5395 "parse_stream returned %p\n", pipe_list);
5396 return 1;
5397 }
5398 command->group = pipe_list;
5399#if !BB_MMU
5400 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5401 command->group_as_string = as_string;
5402 debug_printf_parse("end of group, remembering as:'%s'\n",
5403 command->group_as_string);
5404#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005405 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005406 debug_printf_parse("parse_group return 0\n");
5407 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005408 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005409}
5410
Mike Frysinger98c52642009-04-02 10:02:37 +00005411#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005412/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005413static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005414/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005415static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005416{
5417 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005418 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005419 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005420 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005421 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005422 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005423 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005424 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005425 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005426 }
5427}
5428/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005429static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005430{
5431 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005432 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005433 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005434 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005435 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005436 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005437 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005438 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005439 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005440 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005441 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005442 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005443 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005444 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005445 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005446 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005447 continue;
5448 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005449 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005450 }
5451}
5452/* Process `cmd` - copy contents until "`" is seen. Complicated by
5453 * \` quoting.
5454 * "Within the backquoted style of command substitution, backslash
5455 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5456 * The search for the matching backquote shall be satisfied by the first
5457 * backquote found without a preceding backslash; during this search,
5458 * if a non-escaped backquote is encountered within a shell comment,
5459 * a here-document, an embedded command substitution of the $(command)
5460 * form, or a quoted string, undefined results occur. A single-quoted
5461 * or double-quoted string that begins, but does not end, within the
5462 * "`...`" sequence produces undefined results."
5463 * Example Output
5464 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5465 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005466static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005467{
5468 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005469 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005470 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005471 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005472 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005473 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005474 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005475 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005476 if (ch == '\\') {
5477 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005478 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005479 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005480 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005481 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005482 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005483 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005484 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005485 ch = ch2;
5486 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005487 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005488 }
5489}
5490/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5491 * quoting and nested ()s.
5492 * "With the $(command) style of command substitution, all characters
5493 * following the open parenthesis to the matching closing parenthesis
5494 * constitute the command. Any valid shell script can be used for command,
5495 * except a script consisting solely of redirections which produces
5496 * unspecified results."
5497 * Example Output
5498 * echo $(echo '(TEST)' BEST) (TEST) BEST
5499 * echo $(echo 'TEST)' BEST) TEST) BEST
5500 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5501 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005502static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005503{
5504 int count = 0;
5505 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005506 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005507 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005508 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005509 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005510 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005511 if (ch == '(')
5512 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005513 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005514 if (--count < 0) {
5515 if (!dbl)
5516 break;
5517 if (i_peek(input) == ')') {
5518 i_getch(input);
5519 break;
5520 }
5521 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005522 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005523 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005524 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005525 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005526 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005527 continue;
5528 }
5529 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005530 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005531 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005532 continue;
5533 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005534 if (ch == '\\') {
5535 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005536 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005537 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005538 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005539 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005540 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005541 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005542 continue;
5543 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005544 }
5545}
Mike Frysinger98c52642009-04-02 10:02:37 +00005546#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005547
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005548/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005549#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005550#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005551 handle_dollar(dest, input)
5552#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005553static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005554 o_string *dest,
5555 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005556{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005557 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005558 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005559
5560 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005561 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005562 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005563 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005564 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005565 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005566 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005567 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005568 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005569 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005570 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005571 if (!isalnum(ch) && ch != '_')
5572 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005573 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005574 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005575 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005576 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005577 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005578 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005579 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005580 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005581 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005582 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005583 o_addchr(dest, ch | quote_mask);
5584 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005585 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005586 case '$': /* pid */
5587 case '!': /* last bg pid */
5588 case '?': /* last exit code */
5589 case '#': /* number of args */
5590 case '*': /* args */
5591 case '@': /* args */
5592 goto make_one_char_var;
5593 case '{': {
5594 bool first_char, all_digits;
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005595 int expansion;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005596
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005597 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005598 nommu_addchr(as_string, ch);
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005599 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5600
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00005601 /* TODO: maybe someone will try to escape the '}' */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005602 expansion = 0;
5603 first_char = true;
5604 all_digits = false;
5605 while (1) {
5606 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005607 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005608 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005609 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005610 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005611
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005612 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005613 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005614 /* ${#var}: length of var contents */
5615 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005616 }
5617 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005618 all_digits = true;
5619 goto char_ok;
5620 }
Mike Frysingerdc3bc402009-06-01 14:09:09 -04005621 /* They're being verbose and doing ${?} */
5622 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5623 goto char_ok;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005624 }
5625
5626 if (expansion < 2
5627 && ( (all_digits && !isdigit(ch))
5628 || (!all_digits && !isalnum(ch) && ch != '_')
5629 )
5630 ) {
5631 /* handle parameter expansions
5632 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5633 */
5634 if (first_char)
5635 goto case_default;
5636 switch (ch) {
5637 case ':': /* null modifier */
5638 if (expansion == 0) {
5639 debug_printf_parse(": null modifier\n");
5640 ++expansion;
5641 break;
5642 }
5643 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005644 case '#': /* remove prefix */
5645 case '%': /* remove suffix */
5646 if (expansion == 0) {
5647 debug_printf_parse(": remove suffix/prefix\n");
5648 expansion = 2;
5649 break;
5650 }
5651 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005652 case '-': /* default value */
5653 case '=': /* assign default */
5654 case '+': /* alternative */
5655 case '?': /* error indicate */
5656 debug_printf_parse(": parameter expansion\n");
5657 expansion = 2;
5658 break;
5659 default:
5660 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005661 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005662 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5663 return 1;
5664 }
5665 }
5666 char_ok:
5667 debug_printf_parse(": '%c'\n", ch);
5668 o_addchr(dest, ch | quote_mask);
5669 quote_mask = 0;
5670 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005671 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5673 break;
5674 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005675#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005676 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005677# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005678 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005679# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005680 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005681 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005682# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005683 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005684 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005685 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005686 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5687 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005688# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005689 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005690# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005691 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005692# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005693 if (as_string) {
5694 o_addstr(as_string, dest->data + pos);
5695 o_addchr(as_string, ')');
5696 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005697 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005698# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005699 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005700 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005701 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005702# endif
5703# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005704 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5705 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005706# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005707 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005708# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005709 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005710# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005711 if (as_string) {
5712 o_addstr(as_string, dest->data + pos);
5713 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005714 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005715# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005716 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005717# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005718 break;
5719 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005720#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005721 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005722 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005723 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005724 ch = i_peek(input);
5725 if (isalnum(ch)) { /* it's $_name or $_123 */
5726 ch = '_';
5727 goto make_var;
5728 }
5729 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005730 /* TODO: $_ and $-: */
5731 /* $_ Shell or shell script name; or last argument of last command
5732 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5733 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005734 /* $- Option flags set by set builtin or shell options (-i etc) */
5735 default:
5736 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005737 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005738 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005739 return 0;
5740}
5741
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005742#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005743#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005744 parse_stream_dquoted(dest, input, dquote_end)
5745#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005746static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005747 o_string *dest,
5748 struct in_str *input,
5749 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005750{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005751 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005752 int next;
5753
5754 again:
5755 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005756 if (ch != EOF)
5757 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005758 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005759 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005760 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005761 debug_printf_parse("parse_stream_dquoted return 0\n");
5762 return 0;
5763 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005764 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005765 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005766 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005767 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005768 }
5769 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005770 if (ch != '\n') {
5771 next = i_peek(input);
5772 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005773 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5774 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005775 if (ch == '\\') {
5776 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005777 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005778 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005779 }
5780 /* bash:
5781 * "The backslash retains its special meaning [in "..."]
5782 * only when followed by one of the following characters:
5783 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005784 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005785 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005786 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00005787 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005788 if (ch != '\n') {
5789 o_addqchr(dest, ch);
5790 nommu_addchr(as_string, ch);
5791 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005792 } else {
5793 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00005794 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005795 }
5796 goto again;
5797 }
5798 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005799 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005800 debug_printf_parse("parse_stream_dquoted return 1: "
5801 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005802 return 1;
5803 }
5804 goto again;
5805 }
5806#if ENABLE_HUSH_TICK
5807 if (ch == '`') {
5808 //int pos = dest->length;
5809 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5810 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005811 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005812 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5813 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005814 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005815 }
5816#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005817 o_addQchr(dest, ch);
5818 if (ch == '='
5819 && (dest->o_assignment == MAYBE_ASSIGNMENT
5820 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005821 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00005822 ) {
5823 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5824 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005825 goto again;
5826}
5827
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005828/*
5829 * Scan input until EOF or end_trigger char.
5830 * Return a list of pipes to execute, or NULL on EOF
5831 * or if end_trigger character is met.
5832 * On syntax error, exit is shell is not interactive,
5833 * reset parsing machinery and start parsing anew,
5834 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005835 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005836static struct pipe *parse_stream(char **pstring,
5837 struct in_str *input,
5838 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005839{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005840 struct parse_context ctx;
5841 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005842 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005843 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005844
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005845 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00005846 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005847 * found. When recursing, quote state is passed in via dest->o_escape.
5848 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005849 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005850 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005851 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005852
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005853 G.ifs = get_local_var_value("IFS");
5854 if (G.ifs == NULL)
5855 G.ifs = " \t\n";
5856
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005857 reset:
5858#if ENABLE_HUSH_INTERACTIVE
5859 input->promptmode = 0; /* PS1 */
5860#endif
5861 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5862 initialize_context(&ctx);
5863 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005864 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005865 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005866 const char *is_ifs;
5867 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005868 int ch;
5869 int next;
5870 int redir_fd;
5871 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005872
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005873 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005874 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005875 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005876 goto parse_error;
5877 }
5878 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005879 is_in_dquote = 0;
5880 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005881 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005882 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5883 ch, ch, dest.o_escape);
5884 if (ch == EOF) {
5885 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005886
5887 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005888 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005889 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005890 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005891 /* end_trigger == '}' case errors out earlier,
5892 * checking only ')' */
5893 if (end_trigger == ')') {
5894 syntax_error_unterm_ch('('); /* exits */
5895 /* goto parse_error; */
5896 }
5897
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005898 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005899 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005900 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005901 o_free(&dest);
5902 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005903 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005904 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005905 /* (this makes bare "&" cmd a no-op.
5906 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005907 if (pi->num_cmds == 0
5908 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5909 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005910 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005911 pi = NULL;
5912 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005913#if !BB_MMU
5914 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5915 if (pstring)
5916 *pstring = ctx.as_string.data;
5917 else
5918 o_free_unsafe(&ctx.as_string);
5919#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005920 debug_leave();
5921 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005922 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005923 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005924 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005925 is_ifs = strchr(G.ifs, ch);
5926 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005927 "\\$\"" IF_HUSH_TICK("`") /* always special */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005928 , ch);
5929
5930 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005931 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005932 o_addQchr(&dest, ch);
5933 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5934 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005935 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005936 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005937 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005938 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005939 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005940 continue;
5941 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005942
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005943 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005944 if (done_word(&dest, &ctx)) {
5945 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005946 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005947 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00005948#if ENABLE_HUSH_CASE
5949 /* "case ... in <newline> word) ..." -
5950 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005951 if (ctx.command->argv == NULL
5952 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00005953 ) {
5954 continue;
5955 }
5956#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005957 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005958 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005959 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5960 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005961 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005962 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005963 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005964 heredoc_cnt = 0;
5965 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005966 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005967 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00005968 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005969 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005970 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005971 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005972
5973 /* "cmd}" or "cmd }..." without semicolon or &:
5974 * } is an ordinary char in this case, even inside { cmd; }
5975 * Pathological example: { ""}; } should exec "}" cmd
5976 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005977 if (ch == '}') {
5978 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5979 || dest.length != 0 /* word} */
5980 || dest.o_quoted /* ""} */
5981 ) {
5982 goto ordinary_char;
5983 }
5984 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5985 goto skip_end_trigger;
5986 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005987 }
5988
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005989 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005990 && (ch != ';' || heredoc_cnt == 0)
5991#if ENABLE_HUSH_CASE
5992 && (ch != ')'
5993 || ctx.ctx_res_w != RES_MATCH
5994 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5995 )
5996#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005997 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005998 if (heredoc_cnt) {
5999 /* This is technically valid:
6000 * { cat <<HERE; }; echo Ok
6001 * heredoc
6002 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006003 * HERE
6004 * but we don't support this.
6005 * We require heredoc to be in enclosing {}/(),
6006 * if any.
6007 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006008 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006009 goto parse_error;
6010 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006011 if (done_word(&dest, &ctx)) {
6012 goto parse_error;
6013 }
6014 done_pipe(&ctx, PIPE_SEQ);
6015 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006016 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006017 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006018 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006019 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006020 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006021#if !BB_MMU
6022 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6023 if (pstring)
6024 *pstring = ctx.as_string.data;
6025 else
6026 o_free_unsafe(&ctx.as_string);
6027#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006028 debug_leave();
6029 debug_printf_parse("parse_stream return %p: "
6030 "end_trigger char found\n",
6031 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006032 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006033 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006034 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006035 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006036 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006037 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006038
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006039 next = '\0';
6040 if (ch != '\n') {
6041 next = i_peek(input);
6042 }
6043
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006044 /* Catch <, > before deciding whether this word is
6045 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6046 switch (ch) {
6047 case '>':
6048 redir_fd = redirect_opt_num(&dest);
6049 if (done_word(&dest, &ctx)) {
6050 goto parse_error;
6051 }
6052 redir_style = REDIRECT_OVERWRITE;
6053 if (next == '>') {
6054 redir_style = REDIRECT_APPEND;
6055 ch = i_getch(input);
6056 nommu_addchr(&ctx.as_string, ch);
6057 }
6058#if 0
6059 else if (next == '(') {
6060 syntax_error(">(process) not supported");
6061 goto parse_error;
6062 }
6063#endif
6064 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6065 goto parse_error;
6066 continue; /* back to top of while (1) */
6067 case '<':
6068 redir_fd = redirect_opt_num(&dest);
6069 if (done_word(&dest, &ctx)) {
6070 goto parse_error;
6071 }
6072 redir_style = REDIRECT_INPUT;
6073 if (next == '<') {
6074 redir_style = REDIRECT_HEREDOC;
6075 heredoc_cnt++;
6076 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6077 ch = i_getch(input);
6078 nommu_addchr(&ctx.as_string, ch);
6079 } else if (next == '>') {
6080 redir_style = REDIRECT_IO;
6081 ch = i_getch(input);
6082 nommu_addchr(&ctx.as_string, ch);
6083 }
6084#if 0
6085 else if (next == '(') {
6086 syntax_error("<(process) not supported");
6087 goto parse_error;
6088 }
6089#endif
6090 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6091 goto parse_error;
6092 continue; /* back to top of while (1) */
6093 }
6094
6095 if (dest.o_assignment == MAYBE_ASSIGNMENT
6096 /* check that we are not in word in "a=1 2>word b=1": */
6097 && !ctx.pending_redirect
6098 ) {
6099 /* ch is a special char and thus this word
6100 * cannot be an assignment */
6101 dest.o_assignment = NOT_ASSIGNMENT;
6102 }
6103
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006104 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6105
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006106 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006107 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006108 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006109 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006110 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006111 if (ch == EOF || ch == '\n')
6112 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006113 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006114 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006115 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006116 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006117 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006118 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006119 }
6120 break;
6121 case '\\':
6122 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006123 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006124 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006125 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006126 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006127 if (ch != '\n') {
6128 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006129 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006130 o_addchr(&dest, ch);
6131 nommu_addchr(&ctx.as_string, ch);
6132 /* Example: echo Hello \2>file
6133 * we need to know that word 2 is quoted */
6134 dest.o_quoted = 1;
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006135 } else {
6136#if !BB_MMU
6137 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6138 ctx.as_string.data[--ctx.as_string.length] = '\0';
6139#endif
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006140 }
Eric Andersen25f27032001-04-26 23:22:31 +00006141 break;
6142 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006143 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006144 debug_printf_parse("parse_stream parse error: "
6145 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006146 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006147 }
Eric Andersen25f27032001-04-26 23:22:31 +00006148 break;
6149 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006150 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006151 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006152 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006153 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006154 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006155 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006156 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006157 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006158 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006159 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006160 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006161 }
Eric Andersen25f27032001-04-26 23:22:31 +00006162 break;
6163 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006164 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006165 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006166 if (dest.o_assignment == NOT_ASSIGNMENT)
6167 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006168 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006169#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006170 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006171#if !BB_MMU
6172 int pos;
6173#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006174 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6175 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006176#if !BB_MMU
6177 pos = dest.length;
6178#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006179 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006180#if !BB_MMU
6181 o_addstr(&ctx.as_string, dest.data + pos);
6182 o_addchr(&ctx.as_string, '`');
6183#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006184 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6185 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006186 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006187 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006188#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006189 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006190#if ENABLE_HUSH_CASE
6191 case_semi:
6192#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006193 if (done_word(&dest, &ctx)) {
6194 goto parse_error;
6195 }
6196 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006197#if ENABLE_HUSH_CASE
6198 /* Eat multiple semicolons, detect
6199 * whether it means something special */
6200 while (1) {
6201 ch = i_peek(input);
6202 if (ch != ';')
6203 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006204 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006205 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006206 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006207 ctx.ctx_dsemicolon = 1;
6208 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006209 break;
6210 }
6211 }
6212#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006213 new_cmd:
6214 /* We just finished a cmd. New one may start
6215 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006216 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006217 break;
6218 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006219 if (done_word(&dest, &ctx)) {
6220 goto parse_error;
6221 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006222 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006223 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006224 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006225 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006226 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006227 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006228 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006229 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006230 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006231 if (done_word(&dest, &ctx)) {
6232 goto parse_error;
6233 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006234#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006235 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006236 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006237#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006238 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006239 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006240 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006241 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006242 } else {
6243 /* we could pick up a file descriptor choice here
6244 * with redirect_opt_num(), but bash doesn't do it.
6245 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006246 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00006247 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006248 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006249 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006250#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006251 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006252 if (ctx.ctx_res_w == RES_MATCH
6253 && ctx.command->argv == NULL /* not (word|(... */
6254 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006255 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006256 ) {
6257 continue;
6258 }
6259#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006260 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006261 if (parse_group(&dest, &ctx, input, ch) != 0) {
6262 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006263 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006264 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006265 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006266#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006267 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006268 goto case_semi;
6269#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006270 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006271 /* proper use of this character is caught by end_trigger:
6272 * if we see {, we call parse_group(..., end_trigger='}')
6273 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006274 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006275 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006276 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006277 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006278 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006279 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006280 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006281
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006282 parse_error:
6283 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006284 struct parse_context *pctx;
6285 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006286
6287 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006288 * Sample for finding leaks on syntax error recovery path.
6289 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006290 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006291 * Samples to catch leaks at execution:
6292 * while if (true | {true;}); then echo ok; fi; do break; done
6293 * 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 +00006294 */
6295 pctx = &ctx;
6296 do {
6297 /* Update pipe/command counts,
6298 * otherwise freeing may miss some */
6299 done_pipe(pctx, PIPE_SEQ);
6300 debug_printf_clean("freeing list %p from ctx %p\n",
6301 pctx->list_head, pctx);
6302 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006303 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006304 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006305#if !BB_MMU
6306 o_free_unsafe(&pctx->as_string);
6307#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006308 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006309 if (pctx != &ctx) {
6310 free(pctx);
6311 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006312 IF_HAS_KEYWORDS(pctx = p2;)
6313 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006314 /* Free text, clear all dest fields */
6315 o_free(&dest);
6316 /* If we are not in top-level parse, we return,
6317 * our caller will propagate error.
6318 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006319 if (end_trigger != ';') {
6320#if !BB_MMU
6321 if (pstring)
6322 *pstring = NULL;
6323#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006324 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006325 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006326 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006327 /* Discard cached input, force prompt */
6328 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006329 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006330 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006331 }
Eric Andersen25f27032001-04-26 23:22:31 +00006332}
6333
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006334/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006335 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6336 * end_trigger controls how often we stop parsing
6337 * NUL: parse all, execute, return
6338 * ';': parse till ';' or newline, execute, repeat till EOF
6339 */
6340static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006341{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006342 while (1) {
6343 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006344
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006345 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006346 if (!pipe_list) /* EOF */
6347 break;
6348 debug_print_tree(pipe_list, 0);
6349 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6350 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006351 }
Eric Andersen25f27032001-04-26 23:22:31 +00006352}
6353
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006354static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006355{
6356 struct in_str input;
6357 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006358 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006359}
6360
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006361static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006362{
Eric Andersen25f27032001-04-26 23:22:31 +00006363 struct in_str input;
6364 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006365 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006366}
6367
Denis Vlasenkof9375282009-04-05 19:13:39 +00006368/* Called a few times only (or even once if "sh -c") */
6369static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006370{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006371 unsigned sig;
6372 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006373
Denis Vlasenkof9375282009-04-05 19:13:39 +00006374 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006375 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006376 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006377 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006378 mask |= SPECIAL_JOB_SIGS;
6379 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006380 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006381
Denis Vlasenkof9375282009-04-05 19:13:39 +00006382 if (!second_time)
6383 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6384 sig = 0;
6385 while (mask) {
6386 if (mask & 1)
6387 sigaddset(&G.blocked_set, sig);
6388 mask >>= 1;
6389 sig++;
6390 }
6391 sigdelset(&G.blocked_set, SIGCHLD);
6392
6393 sigprocmask(SIG_SETMASK, &G.blocked_set,
6394 second_time ? NULL : &G.inherited_set);
6395 /* POSIX allows shell to re-enable SIGCHLD
6396 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006397#if ENABLE_HUSH_FAST
6398 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006399 if (!second_time)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006400 signal(SIGCHLD, SIGCHLD_handler);
6401#else
6402 if (!second_time)
6403 signal(SIGCHLD, SIG_DFL);
6404#endif
Denis Vlasenkof9375282009-04-05 19:13:39 +00006405}
6406
6407#if ENABLE_HUSH_JOB
6408/* helper */
6409static void maybe_set_to_sigexit(int sig)
6410{
6411 void (*handler)(int);
6412 /* non_DFL_mask'ed signals are, well, masked,
6413 * no need to set handler for them.
6414 */
6415 if (!((G.non_DFL_mask >> sig) & 1)) {
6416 handler = signal(sig, sigexit);
6417 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6418 signal(sig, handler);
6419 }
6420}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006421/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006422static void set_fatal_handlers(void)
6423{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006424 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006425 if (HUSH_DEBUG) {
6426 maybe_set_to_sigexit(SIGILL );
6427 maybe_set_to_sigexit(SIGFPE );
6428 maybe_set_to_sigexit(SIGBUS );
6429 maybe_set_to_sigexit(SIGSEGV);
6430 maybe_set_to_sigexit(SIGTRAP);
6431 } /* else: hush is perfect. what SEGV? */
6432 maybe_set_to_sigexit(SIGABRT);
6433 /* bash 3.2 seems to handle these just like 'fatal' ones */
6434 maybe_set_to_sigexit(SIGPIPE);
6435 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006436 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006437 * if we aren't interactive... but in this case
6438 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006439 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006440 /*maybe_set_to_sigexit(SIGTERM);*/
6441 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006442}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006443#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006444
Denis Vlasenkod5762932009-03-31 11:22:57 +00006445static int set_mode(const char cstate, const char mode)
6446{
6447 int state = (cstate == '-' ? 1 : 0);
6448 switch (mode) {
6449 case 'n': G.fake_mode = state; break;
6450 case 'x': /*G.debug_mode = state;*/ break;
6451 default: return EXIT_FAILURE;
6452 }
6453 return EXIT_SUCCESS;
6454}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006455
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006456int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006457int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006458{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006459 static const struct variable const_shell_ver = {
6460 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006461 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006462 .max_len = 1, /* 0 can provoke free(name) */
6463 .flg_export = 1,
6464 .flg_read_only = 1,
6465 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00006466 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00006467 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006468 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006469 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006470 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006471
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006472 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006473 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006474 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006475#if !BB_MMU
6476 G.argv0_for_re_execing = argv[0];
6477#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006478 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006479 G.shell_ver = const_shell_ver; /* copying struct here */
6480 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006481 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006482 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6483 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006484 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006485 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006486 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006487 if (e) while (*e) {
6488 char *value = strchr(*e, '=');
6489 if (value) { /* paranoia */
6490 cur_var->next = xzalloc(sizeof(*cur_var));
6491 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006492 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006493 cur_var->max_len = strlen(*e);
6494 cur_var->flg_export = 1;
6495 }
6496 e++;
6497 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006498 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006499 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02006500 putenv((char *)hush_version_str);
6501
6502 /* Export PWD */
6503 set_pwd_var(/*exp:*/ 1);
6504 /* bash also exports SHLVL and _,
6505 * and sets (but doesn't export) the following variables:
6506 * BASH=/bin/bash
6507 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6508 * BASH_VERSION='3.2.0(1)-release'
6509 * HOSTTYPE=i386
6510 * MACHTYPE=i386-pc-linux-gnu
6511 * OSTYPE=linux-gnu
6512 * HOSTNAME=<xxxxxxxxxx>
6513 * PPID=<NNNNN>
6514 * EUID=<NNNNN>
6515 * UID=<NNNNN>
6516 * GROUPS=()
6517 * LINES=<NNN>
6518 * COLUMNS=<NNN>
6519 * BASH_ARGC=()
6520 * BASH_ARGV=()
6521 * BASH_LINENO=()
6522 * BASH_SOURCE=()
6523 * DIRSTACK=()
6524 * PIPESTATUS=([0]="0")
6525 * HISTFILE=/<xxx>/.bash_history
6526 * HISTFILESIZE=500
6527 * HISTSIZE=500
6528 * MAILCHECK=60
6529 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6530 * SHELL=/bin/bash
6531 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6532 * TERM=dumb
6533 * OPTERR=1
6534 * OPTIND=1
6535 * IFS=$' \t\n'
6536 * PS1='\s-\v\$ '
6537 * PS2='> '
6538 * PS4='+ '
6539 */
6540
Denis Vlasenko38f63192007-01-22 09:03:07 +00006541#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006542 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006543#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006544 G.global_argc = argc;
6545 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006546 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006547 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006548
Denis Vlasenkoed782372009-04-10 00:45:02 +00006549 if (setjmp(die_jmp)) {
6550 /* xfunc has failed! die die die */
6551 /* no EXIT traps, this is an escape hatch! */
6552 G.exiting = 1;
6553 hush_exit(xfunc_error_retval);
6554 }
6555
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006556 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006557 * block_signals(0) if we are going to execute "sh <script>",
6558 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006559 * If we later decide that we are interactive, we run block_signals(0)
6560 * (or re-run block_signals(1) if we ran block_signals(0) before)
6561 * in order to intercept (more) signals.
6562 */
6563
6564 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006565 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006566 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006567 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02006568 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006569#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006570 "<:$:R:V:"
6571# if ENABLE_HUSH_FUNCTIONS
6572 "F:"
6573# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006574#endif
6575 );
6576 if (opt <= 0)
6577 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006578 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006579 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006580 /* Possibilities:
6581 * sh ... -c 'script'
6582 * sh ... -c 'script' ARG0 [ARG1...]
6583 * On NOMMU, if builtin_argc != 0,
6584 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6585 * "" needs to be replaced with NULL
6586 * and BARGV vector fed to builtin function.
6587 * Note: this form never happens:
6588 * sh ... -c 'builtin' [BARGV...] ""
6589 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006590 if (!G.root_pid)
6591 G.root_pid = getpid();
Denis Vlasenko87a86552008-07-29 19:43:10 +00006592 G.global_argv = argv + optind;
6593 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006594 if (builtin_argc) {
6595 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6596 const struct built_in_command *x;
6597
6598 block_signals(0); /* 0: called 1st time */
6599 x = find_builtin(optarg);
6600 if (x) { /* paranoia */
6601 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6602 G.global_argv += builtin_argc;
6603 G.global_argv[-1] = NULL; /* replace "" */
6604 G.last_exitcode = x->function(argv + optind - 1);
6605 }
6606 goto final_return;
6607 }
6608 if (!G.global_argv[0]) {
6609 /* -c 'script' (no params): prevent empty $0 */
6610 G.global_argv--; /* points to argv[i] of 'script' */
6611 G.global_argv[0] = argv[0];
6612 G.global_argc--;
6613 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006614 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006615 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006616 goto final_return;
6617 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00006618 /* Well, we cannot just declare interactiveness,
6619 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006620 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006621 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006622 case 's':
6623 /* "-s" means "read from stdin", but this is how we always
6624 * operate, so simply do nothing here. */
6625 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006626#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00006627 case '<': /* "big heredoc" support */
6628 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6629 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006630 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006631 G.root_pid = bb_strtou(optarg, &optarg, 16);
6632 optarg++;
6633 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6634 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006635 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006636 optarg++;
6637 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006638# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006639 optarg++;
6640 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006641# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006642 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006643 case 'R':
6644 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02006645 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006646 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00006647# if ENABLE_HUSH_FUNCTIONS
6648 case 'F': {
6649 struct function *funcp = new_function(optarg);
6650 /* funcp->name is already set to optarg */
6651 /* funcp->body is set to NULL. It's a special case. */
6652 funcp->body_as_string = argv[optind];
6653 optind++;
6654 break;
6655 }
6656# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006657#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006658 case 'n':
6659 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00006660 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006661 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006662 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006663#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006664 fprintf(stderr, "Usage: sh [FILE]...\n"
6665 " or: sh -c command [args]...\n\n");
6666 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006667#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006668 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006669#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006670 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006671 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006672
6673 if (!G.root_pid)
6674 G.root_pid = getpid();
Denis Vlasenkof9375282009-04-05 19:13:39 +00006675
6676 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006677 if (argv[0] && argv[0][0] == '-') {
6678 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006679 debug_printf("sourcing /etc/profile\n");
6680 input = fopen_for_read("/etc/profile");
6681 if (input != NULL) {
6682 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00006683 block_signals(0); /* 0: called 1st time */
6684 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006685 parse_and_run_file(input);
6686 fclose(input);
6687 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006688 /* bash: after sourcing /etc/profile,
6689 * tries to source (in the given order):
6690 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006691 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006692 * bash also sources ~/.bash_logout on exit.
6693 * If called as sh, skips .bash_XXX files.
6694 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006695 }
6696
Denis Vlasenkof9375282009-04-05 19:13:39 +00006697 if (argv[optind]) {
6698 FILE *input;
6699 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006700 * "bash <script>" (which is never interactive (unless -i?))
6701 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00006702 * If called as sh, does the same but with $ENV.
6703 */
6704 debug_printf("running script '%s'\n", argv[optind]);
6705 G.global_argv = argv + optind;
6706 G.global_argc = argc - optind;
6707 input = xfopen_for_read(argv[optind]);
6708 close_on_exec_on(fileno(input));
6709 if (!signal_mask_is_inited)
6710 block_signals(0); /* 0: called 1st time */
6711 parse_and_run_file(input);
6712#if ENABLE_FEATURE_CLEAN_UP
6713 fclose(input);
6714#endif
6715 goto final_return;
6716 }
6717
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006718 /* Up to here, shell was non-interactive. Now it may become one.
6719 * NB: don't forget to (re)run block_signals(0/1) as needed.
6720 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006721
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006722 /* A shell is interactive if the '-i' flag was given,
6723 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00006724 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00006725 * no arguments remaining or the -s flag given
6726 * standard input is a terminal
6727 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00006728 * Refer to Posix.2, the description of the 'sh' utility.
6729 */
6730#if ENABLE_HUSH_JOB
6731 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04006732 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6733 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6734 if (G_saved_tty_pgrp < 0)
6735 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006736
6737 /* try to dup stdin to high fd#, >= 255 */
6738 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6739 if (G_interactive_fd < 0) {
6740 /* try to dup to any fd */
6741 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006742 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006743 /* give up */
6744 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04006745 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006746 }
6747 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006748// TODO: track & disallow any attempts of user
6749// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00006750 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006751 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006752 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006753 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006754
Mike Frysinger38478a62009-05-20 04:48:06 -04006755 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006756 /* If we were run as 'hush &', sleep until we are
6757 * in the foreground (tty pgrp == our pgrp).
6758 * If we get started under a job aware app (like bash),
6759 * make sure we are now in charge so we don't fight over
6760 * who gets the foreground */
6761 while (1) {
6762 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04006763 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6764 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006765 break;
6766 /* send TTIN to ourself (should stop us) */
6767 kill(- shell_pgrp, SIGTTIN);
6768 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006769 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006770
Denis Vlasenkof9375282009-04-05 19:13:39 +00006771 /* Block some signals */
6772 block_signals(signal_mask_is_inited);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006773
Mike Frysinger38478a62009-05-20 04:48:06 -04006774 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006775 /* Set other signals to restore saved_tty_pgrp */
6776 set_fatal_handlers();
6777 /* Put ourselves in our own process group
6778 * (bash, too, does this only if ctty is available) */
6779 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6780 /* Grab control of the terminal */
6781 tcsetpgrp(G_interactive_fd, getpid());
6782 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00006783 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00006784 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006785 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006786 } else if (!signal_mask_is_inited) {
6787 block_signals(0); /* 0: called 1st time */
6788 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006789#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00006790 /* No job control compiled in, only prompt/line editing */
6791 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006792 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6793 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006794 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006795 G_interactive_fd = dup(STDIN_FILENO);
6796 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006797 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006798 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006799 }
6800 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006801 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006802 close_on_exec_on(G_interactive_fd);
6803 block_signals(signal_mask_is_inited);
6804 } else if (!signal_mask_is_inited) {
6805 block_signals(0);
6806 }
6807#else
6808 /* We have interactiveness code disabled */
6809 if (!signal_mask_is_inited) {
6810 block_signals(0);
6811 }
6812#endif
6813 /* bash:
6814 * if interactive but not a login shell, sources ~/.bashrc
6815 * (--norc turns this off, --rcfile <file> overrides)
6816 */
6817
6818 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Mike Frysinger258275d2009-04-05 21:19:43 +00006819 printf("\n\n%s hush - the humble shell\n", bb_banner);
Mike Frysinger26cf2832009-04-24 06:40:30 +00006820 if (ENABLE_HUSH_HELP)
6821 puts("Enter 'help' for a list of built-in commands.");
6822 puts("");
Mike Frysingerb2705e12009-03-23 08:44:02 +00006823 }
6824
Denis Vlasenkof9375282009-04-05 19:13:39 +00006825 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00006826
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006827 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00006828#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00006829 if (G.cwd != bb_msg_unknown)
6830 free((char*)G.cwd);
6831 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006832 while (cur_var) {
6833 struct variable *tmp = cur_var;
6834 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006835 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006836 cur_var = cur_var->next;
6837 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00006838 }
Eric Andersen25f27032001-04-26 23:22:31 +00006839#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006840 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00006841}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006842
6843
6844#if ENABLE_LASH
6845int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6846int lash_main(int argc, char **argv)
6847{
Denys Vlasenko07934912009-08-20 03:40:04 +02006848 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006849 return hush_main(argc, argv);
6850}
6851#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006852
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02006853#if ENABLE_MSH
6854int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6855int msh_main(int argc, char **argv)
6856{
6857 //bb_error_msg("msh is deprecated, please use hush instead");
6858 return hush_main(argc, argv);
6859}
6860#endif
6861
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006862
6863/*
6864 * Built-ins
6865 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006866static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006867{
6868 return 0;
6869}
6870
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006871static int FAST_FUNC builtin_test(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006872{
6873 int argc = 0;
6874 while (*argv) {
6875 argc++;
6876 argv++;
6877 }
6878 return test_main(argc, argv - argc);
6879}
6880
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006881static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006882{
6883 int argc = 0;
6884 while (*argv) {
6885 argc++;
6886 argv++;
6887 }
6888 return echo_main(argc, argv - argc);
6889}
6890
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006891static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006892{
6893 int rcode = EXIT_SUCCESS;
6894
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006895 if (*++argv) {
6896 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006897 /* bash:
6898 * eval "echo Hi; done" ("done" is syntax error):
6899 * "echo Hi" will not execute too.
6900 */
6901 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006902 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006903 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006904 }
6905 return rcode;
6906}
6907
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006908static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006909{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006910 const char *newdir = argv[1];
6911 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006912 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006913 * bash says "bash: cd: HOME not set" and does nothing
6914 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006915 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02006916 const char *home = get_local_var_value("HOME");
6917 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006918 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006919 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006920 /* Mimic bash message exactly */
6921 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006922 return EXIT_FAILURE;
6923 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006924 /* Read current dir (get_cwd(1) is inside) and set PWD.
6925 * Note: do not enforce exporting. If PWD was unset or unexported,
6926 * set it again, but do not export. bash does the same.
6927 */
6928 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006929 return EXIT_SUCCESS;
6930}
6931
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006932static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006933{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006934 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006935 return EXIT_SUCCESS; /* bash does this */
6936 {
6937#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006938 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006939#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006940 /* TODO: if exec fails, bash does NOT exit! We do... */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006941 pseudo_exec_argv(&dummy, argv, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006942 /* never returns */
6943 }
6944}
6945
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006946static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006947{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00006948 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00006949
6950 /* interactive bash:
6951 * # trap "echo EEE" EXIT
6952 * # exit
6953 * exit
6954 * There are stopped jobs.
6955 * (if there are _stopped_ jobs, running ones don't count)
6956 * # exit
6957 * exit
6958 # EEE (then bash exits)
6959 *
6960 * we can use G.exiting = -1 as indicator "last cmd was exit"
6961 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00006962
6963 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006964 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006965 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006966 /* mimic bash: exit 123abc == exit 255 + error msg */
6967 xfunc_error_retval = 255;
6968 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006969 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006970}
6971
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006972static void print_escaped(const char *s)
6973{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006974 if (*s == '\'')
6975 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006976 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006977 const char *p = strchrnul(s, '\'');
6978 /* print 'xxxx', possibly just '' */
6979 printf("'%.*s'", (int)(p - s), s);
6980 if (*p == '\0')
6981 break;
6982 s = p;
6983 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006984 /* s points to '; print "'''...'''" */
6985 putchar('"');
6986 do putchar('\''); while (*++s == '\'');
6987 putchar('"');
6988 } while (*s);
6989}
6990
Denys Vlasenko295fef82009-06-03 12:47:26 +02006991#if !ENABLE_HUSH_LOCAL
6992#define helper_export_local(argv, exp, lvl) \
6993 helper_export_local(argv, exp)
6994#endif
6995static void helper_export_local(char **argv, int exp, int lvl)
6996{
6997 do {
6998 char *name = *argv;
6999
7000 /* So far we do not check that name is valid (TODO?) */
7001
7002 if (strchr(name, '=') == NULL) {
7003 struct variable *var;
7004
7005 var = get_local_var(name);
7006 if (exp == -1) { /* unexporting? */
7007 /* export -n NAME (without =VALUE) */
7008 if (var) {
7009 var->flg_export = 0;
7010 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7011 unsetenv(name);
7012 } /* else: export -n NOT_EXISTING_VAR: no-op */
7013 continue;
7014 }
7015 if (exp == 1) { /* exporting? */
7016 /* export NAME (without =VALUE) */
7017 if (var) {
7018 var->flg_export = 1;
7019 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7020 putenv(var->varstr);
7021 continue;
7022 }
7023 }
7024 /* Exporting non-existing variable.
7025 * bash does not put it in environment,
7026 * but remembers that it is exported,
7027 * and does put it in env when it is set later.
7028 * We just set it to "" and export. */
7029 /* Or, it's "local NAME" (without =VALUE).
7030 * bash sets the value to "". */
7031 name = xasprintf("%s=", name);
7032 } else {
7033 /* (Un)exporting/making local NAME=VALUE */
7034 name = xstrdup(name);
7035 }
7036 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7037 } while (*++argv);
7038}
7039
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007040static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007041{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007042 unsigned opt_unexport;
7043
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007044#if ENABLE_HUSH_EXPORT_N
7045 /* "!": do not abort on errors */
7046 opt_unexport = getopt32(argv, "!n");
7047 if (opt_unexport == (uint32_t)-1)
7048 return EXIT_FAILURE;
7049 argv += optind;
7050#else
7051 opt_unexport = 0;
7052 argv++;
7053#endif
7054
7055 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007056 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007057 if (e) {
7058 while (*e) {
7059#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007060 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007061#else
7062 /* ash emits: export VAR='VAL'
7063 * bash: declare -x VAR="VAL"
7064 * we follow ash example */
7065 const char *s = *e++;
7066 const char *p = strchr(s, '=');
7067
7068 if (!p) /* wtf? take next variable */
7069 continue;
7070 /* export var= */
7071 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007072 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007073 putchar('\n');
7074#endif
7075 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007076 /*fflush(stdout); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007077 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007078 return EXIT_SUCCESS;
7079 }
7080
Denys Vlasenko295fef82009-06-03 12:47:26 +02007081 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007082
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007083 return EXIT_SUCCESS;
7084}
7085
Denys Vlasenko295fef82009-06-03 12:47:26 +02007086#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007087static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007088{
7089 if (G.func_nest_level == 0) {
7090 bb_error_msg("%s: not in a function", argv[0]);
7091 return EXIT_FAILURE; /* bash compat */
7092 }
7093 helper_export_local(argv, 0, G.func_nest_level);
7094 return EXIT_SUCCESS;
7095}
7096#endif
7097
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007098static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007099{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007100 int sig;
7101 char *new_cmd;
7102
7103 if (!G.traps)
7104 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7105
7106 argv++;
7107 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007108 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007109 /* No args: print all trapped */
7110 for (i = 0; i < NSIG; ++i) {
7111 if (G.traps[i]) {
7112 printf("trap -- ");
7113 print_escaped(G.traps[i]);
Denys Vlasenko91836ba2009-09-23 01:46:19 +02007114 /* bash compat: it says SIGxxx, not just xxx */
Denys Vlasenko2f7894b2009-09-24 01:43:21 +02007115 printf(" %s%s\n", i == 0 ? "" : "SIG", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007116 }
7117 }
7118 /*fflush(stdout); - done after each builtin anyway */
7119 return EXIT_SUCCESS;
7120 }
7121
7122 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007123 /* If first arg is a number: reset all specified signals */
7124 sig = bb_strtou(*argv, NULL, 10);
7125 if (errno == 0) {
7126 int ret;
7127 process_sig_list:
7128 ret = EXIT_SUCCESS;
7129 while (*argv) {
7130 sig = get_signum(*argv++);
7131 if (sig < 0 || sig >= NSIG) {
7132 ret = EXIT_FAILURE;
7133 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007134 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007135 continue;
7136 }
7137
7138 free(G.traps[sig]);
7139 G.traps[sig] = xstrdup(new_cmd);
7140
7141 debug_printf("trap: setting SIG%s (%i) to '%s'",
7142 get_signame(sig), sig, G.traps[sig]);
7143
7144 /* There is no signal for 0 (EXIT) */
7145 if (sig == 0)
7146 continue;
7147
7148 if (new_cmd) {
7149 sigaddset(&G.blocked_set, sig);
7150 } else {
7151 /* There was a trap handler, we are removing it
7152 * (if sig has non-DFL handling,
7153 * we don't need to do anything) */
7154 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7155 continue;
7156 sigdelset(&G.blocked_set, sig);
7157 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007158 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007159 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007160 return ret;
7161 }
7162
7163 if (!argv[1]) { /* no second arg */
7164 bb_error_msg("trap: invalid arguments");
7165 return EXIT_FAILURE;
7166 }
7167
7168 /* First arg is "-": reset all specified to default */
7169 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7170 /* Everything else: set arg as signal handler
7171 * (includes "" case, which ignores signal) */
7172 if (argv[0][0] == '-') {
7173 if (argv[0][1] == '\0') { /* "-" */
7174 /* new_cmd remains NULL: "reset these sigs" */
7175 goto reset_traps;
7176 }
7177 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7178 argv++;
7179 }
7180 /* else: "-something", no special meaning */
7181 }
7182 new_cmd = *argv;
7183 reset_traps:
7184 argv++;
7185 goto process_sig_list;
7186}
7187
Mike Frysinger93cadc22009-05-27 17:06:25 -04007188/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007189static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007190{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007191 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007192
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007193 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007194 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007195 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007196
7197 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007198 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007199 type = "an alias";*/
7200#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007201 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007202 type = "a function";
7203#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007204 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007205 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007206 else if ((path = find_in_path(*argv)) != NULL)
7207 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007208 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007209 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007210 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007211 continue;
7212 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007213
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007214 printf("%s is %s\n", *argv, type);
7215 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007216 }
7217
7218 return ret;
7219}
7220
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007221#if ENABLE_HUSH_JOB
7222/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007223static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007224{
7225 int i, jobnum;
7226 struct pipe *pi;
7227
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007228 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007229 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007230
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007231 /* If they gave us no args, assume they want the last backgrounded task */
7232 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007233 for (pi = G.job_list; pi; pi = pi->next) {
7234 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007235 goto found;
7236 }
7237 }
7238 bb_error_msg("%s: no current job", argv[0]);
7239 return EXIT_FAILURE;
7240 }
7241 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7242 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7243 return EXIT_FAILURE;
7244 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007245 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007246 if (pi->jobid == jobnum) {
7247 goto found;
7248 }
7249 }
7250 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7251 return EXIT_FAILURE;
7252 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007253 /* TODO: bash prints a string representation
7254 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007255 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007256 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007257 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007258 }
7259
7260 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007261 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7262 for (i = 0; i < pi->num_cmds; i++) {
7263 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7264 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007265 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007266 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007267
7268 i = kill(- pi->pgrp, SIGCONT);
7269 if (i < 0) {
7270 if (errno == ESRCH) {
7271 delete_finished_bg_job(pi);
7272 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007273 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007274 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007275 }
7276
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007277 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007278 remove_bg_job(pi);
7279 return checkjobs_and_fg_shell(pi);
7280 }
7281 return EXIT_SUCCESS;
7282}
7283#endif
7284
7285#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007286static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007287{
7288 const struct built_in_command *x;
7289
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007290 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007291 "Built-in commands:\n"
7292 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007293 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7294 if (x->descr)
7295 printf("%s\t%s\n", x->cmd, x->descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007296 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007297 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007298 return EXIT_SUCCESS;
7299}
7300#endif
7301
7302#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007303static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007304{
7305 struct pipe *job;
7306 const char *status_string;
7307
Denis Vlasenko87a86552008-07-29 19:43:10 +00007308 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007309 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007310 status_string = "Stopped";
7311 else
7312 status_string = "Running";
7313
7314 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7315 }
7316 return EXIT_SUCCESS;
7317}
7318#endif
7319
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007320#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007321static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007322{
7323 void *p;
7324 unsigned long l;
7325
Denys Vlasenko27726cb2009-09-12 14:48:33 +02007326#ifdef M_TRIM_THRESHOLD
7327 /* Optional. Reduces probability of false positives */
7328 malloc_trim(0);
7329#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007330 /* Crude attempt to find where "free memory" starts,
7331 * sans fragmentation. */
7332 p = malloc(240);
7333 l = (unsigned long)p;
7334 free(p);
7335 p = malloc(3400);
7336 if (l < (unsigned long)p) l = (unsigned long)p;
7337 free(p);
7338
7339 if (!G.memleak_value)
7340 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007341
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007342 l -= G.memleak_value;
7343 if ((long)l < 0)
7344 l = 0;
7345 l /= 1024;
7346 if (l > 127)
7347 l = 127;
7348
7349 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7350 return l;
7351}
7352#endif
7353
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007354static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007355{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007356 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007357 return EXIT_SUCCESS;
7358}
7359
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007360static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007361{
7362 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007363 const char *name = "REPLY";
7364
7365 if (argv[1]) {
7366 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007367 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7368 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007369 if (!is_well_formed_var_name(name, '\0')) {
7370 /* Mimic bash message */
7371 bb_error_msg("read: '%s': not a valid identifier", name);
7372 return 1;
7373 }
7374 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007375
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007376//TODO: bash unbackslashes input, splits words and puts them in argv[i]
7377
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007378 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denys Vlasenko295fef82009-06-03 12:47:26 +02007379 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007380}
7381
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007382/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7383 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007384 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007385 * set [-abCefhmnuvx] [-o option] [argument...]
7386 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007387 * set -- [argument...]
7388 * set -o
7389 * set +o
7390 * Implementations shall support the options in both their hyphen and
7391 * plus-sign forms. These options can also be specified as options to sh.
7392 * Examples:
7393 * Write out all variables and their values: set
7394 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7395 * Turn on the -x and -v options: set -xv
7396 * Unset all positional parameters: set --
7397 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7398 * Set the positional parameters to the expansion of x, even if x expands
7399 * with a leading '-' or '+': set -- $x
7400 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007401 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007402 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007403static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007404{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007405 int n;
7406 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007407 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007408
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007409 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007410 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007411 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007412 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007413 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007414 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007415
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007416 do {
7417 if (!strcmp(arg, "--")) {
7418 ++argv;
7419 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007420 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00007421 if (arg[0] != '+' && arg[0] != '-')
7422 break;
7423 for (n = 1; arg[n]; ++n)
7424 if (set_mode(arg[0], arg[n]))
7425 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007426 } while ((arg = *++argv) != NULL);
7427 /* Now argv[0] is 1st argument */
7428
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007429 if (arg == NULL)
7430 return EXIT_SUCCESS;
7431 set_argv:
7432
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007433 /* NB: G.global_argv[0] ($0) is never freed/changed */
7434 g_argv = G.global_argv;
7435 if (G.global_args_malloced) {
7436 pp = g_argv;
7437 while (*++pp)
7438 free(*pp);
7439 g_argv[1] = NULL;
7440 } else {
7441 G.global_args_malloced = 1;
7442 pp = xzalloc(sizeof(pp[0]) * 2);
7443 pp[0] = g_argv[0]; /* retain $0 */
7444 g_argv = pp;
7445 }
7446 /* This realloc's G.global_argv */
7447 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7448
7449 n = 1;
7450 while (*++pp)
7451 n++;
7452 G.global_argc = n;
7453
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007454 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007455
7456 /* Nothing known, so abort */
7457 error:
7458 bb_error_msg("set: %s: invalid option", arg);
7459 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007460}
7461
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007462static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007463{
7464 int n = 1;
7465 if (argv[1]) {
7466 n = atoi(argv[1]);
7467 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007468 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007469 if (G.global_args_malloced) {
7470 int m = 1;
7471 while (m <= n)
7472 free(G.global_argv[m++]);
7473 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007474 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007475 memmove(&G.global_argv[1], &G.global_argv[n+1],
7476 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007477 return EXIT_SUCCESS;
7478 }
7479 return EXIT_FAILURE;
7480}
7481
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007482static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007483{
Mike Frysinger93cadc22009-05-27 17:06:25 -04007484 char *arg_path;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007485 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007486 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007487#if ENABLE_HUSH_FUNCTIONS
7488 smallint sv_flg;
7489#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007490
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007491 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007492 return EXIT_FAILURE;
7493
Mike Frysinger93cadc22009-05-27 17:06:25 -04007494 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7495 input = fopen_for_read(arg_path);
7496 free(arg_path);
7497 } else
7498 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007499 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007500 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007501 return EXIT_FAILURE;
7502 }
7503 close_on_exec_on(fileno(input));
7504
Mike Frysinger885b6f22009-04-18 21:04:25 +00007505#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007506 sv_flg = G.flag_return_in_progress;
7507 /* "we are inside sourced file, ok to use return" */
7508 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007509#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007510 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007511
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007512 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007513 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007514
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007515 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00007516#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007517 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007518#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007519
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007520 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007521}
7522
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007523static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007524{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007525 int rc;
7526 mode_t mask;
7527
7528 mask = umask(0);
7529 if (argv[1]) {
7530 mode_t old_mask = mask;
7531
7532 mask ^= 0777;
7533 rc = bb_parse_mode(argv[1], &mask);
7534 mask ^= 0777;
7535 if (rc == 0) {
7536 mask = old_mask;
7537 /* bash messages:
7538 * bash: umask: 'q': invalid symbolic mode operator
7539 * bash: umask: 999: octal number out of range
7540 */
7541 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007542 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007543 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007544 rc = 1;
7545 /* Mimic bash */
7546 printf("%04o\n", (unsigned) mask);
7547 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007548 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007549 umask(mask);
7550
7551 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007552}
7553
Mike Frysingerd690f682009-03-30 06:50:54 +00007554/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007555static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007556{
Mike Frysingerd690f682009-03-30 06:50:54 +00007557 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00007558 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00007559
Denis Vlasenko28e67962009-04-26 23:22:40 +00007560 /* "!": do not abort on errors */
7561 /* "+": stop at 1st non-option */
7562 opts = getopt32(argv, "!+vf");
7563 if (opts == (unsigned)-1)
7564 return EXIT_FAILURE;
7565 if (opts == 3) {
7566 bb_error_msg("unset: -v and -f are exclusive");
7567 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00007568 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00007569 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00007570
7571 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007572 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00007573 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007574 if (unset_local_var(*argv)) {
7575 /* unset <nonexistent_var> doesn't fail.
7576 * Error is when one tries to unset RO var.
7577 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00007578 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007579 }
Mike Frysingerd690f682009-03-30 06:50:54 +00007580 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00007581#if ENABLE_HUSH_FUNCTIONS
7582 else {
7583 unset_func(*argv);
7584 }
7585#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007586 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00007587 }
7588 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007589}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007590
Mike Frysinger56bdea12009-03-28 20:01:58 +00007591/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007592static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00007593{
7594 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007595 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007596
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007597 if (*++argv == NULL) {
7598 /* Don't care about wait results */
7599 /* Note 1: must wait until there are no more children */
7600 /* Note 2: must be interruptible */
7601 /* Examples:
7602 * $ sleep 3 & sleep 6 & wait
7603 * [1] 30934 sleep 3
7604 * [2] 30935 sleep 6
7605 * [1] Done sleep 3
7606 * [2] Done sleep 6
7607 * $ sleep 3 & sleep 6 & wait
7608 * [1] 30936 sleep 3
7609 * [2] 30937 sleep 6
7610 * [1] Done sleep 3
7611 * ^C <-- after ~4 sec from keyboard
7612 * $
7613 */
7614 sigaddset(&G.blocked_set, SIGCHLD);
7615 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7616 while (1) {
7617 checkjobs(NULL);
7618 if (errno == ECHILD)
7619 break;
7620 /* Wait for SIGCHLD or any other signal of interest */
7621 /* sigtimedwait with infinite timeout: */
7622 sig = sigwaitinfo(&G.blocked_set, NULL);
7623 if (sig > 0) {
7624 sig = check_and_run_traps(sig);
7625 if (sig && sig != SIGCHLD) { /* see note 2 */
7626 ret = 128 + sig;
7627 break;
7628 }
7629 }
7630 }
7631 sigdelset(&G.blocked_set, SIGCHLD);
7632 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7633 return ret;
7634 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00007635
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007636 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00007637 while (*argv) {
7638 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00007639 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007640 /* mimic bash message */
7641 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007642 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007643 }
7644 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00007645 if (WIFSIGNALED(status))
7646 ret = 128 + WTERMSIG(status);
7647 else if (WIFEXITED(status))
7648 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00007649 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00007650 ret = EXIT_FAILURE;
7651 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007652 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007653 ret = 127;
7654 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00007655 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007656 }
7657
7658 return ret;
7659}
7660
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007661#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7662static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7663{
7664 if (argv[1]) {
7665 def = bb_strtou(argv[1], NULL, 10);
7666 if (errno || def < def_min || argv[2]) {
7667 bb_error_msg("%s: bad arguments", argv[0]);
7668 def = UINT_MAX;
7669 }
7670 }
7671 return def;
7672}
7673#endif
7674
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007675#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007676static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007677{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007678 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007679 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007680 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00007681 return EXIT_SUCCESS; /* bash compat */
7682 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007683 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007684
7685 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7686 if (depth == UINT_MAX)
7687 G.flag_break_continue = BC_BREAK;
7688 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00007689 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007690
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007691 return EXIT_SUCCESS;
7692}
7693
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007694static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007695{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007696 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7697 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007698}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007699#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007700
7701#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007702static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007703{
7704 int rc;
7705
7706 if (G.flag_return_in_progress != -1) {
7707 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7708 return EXIT_FAILURE; /* bash compat */
7709 }
7710
7711 G.flag_return_in_progress = 1;
7712
7713 /* bash:
7714 * out of range: wraps around at 256, does not error out
7715 * non-numeric param:
7716 * f() { false; return qwe; }; f; echo $?
7717 * bash: return: qwe: numeric argument required <== we do this
7718 * 255 <== we also do this
7719 */
7720 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
7721 return rc;
7722}
7723#endif