blob: 866593f77e17c465465d947c21e03ad7f4c33d32 [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.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001114 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001115enum {
1116 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001117 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001118 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001119 | (1 << SIGHUP)
1120 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001121 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001122#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001123 | (1 << SIGTTIN)
1124 | (1 << SIGTTOU)
1125 | (1 << SIGTSTP)
1126#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001127};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001128
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001129#if ENABLE_HUSH_FAST
1130static void SIGCHLD_handler(int sig UNUSED_PARAM)
1131{
1132 G.count_SIGCHLD++;
1133//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1134}
1135#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001136
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001137#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001138
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001139/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1140#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001141/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001142#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1143
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001144/* Restores tty foreground process group, and exits.
1145 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001146 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001147 * or called directly with -EXITCODE.
1148 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001149static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001150static void sigexit(int sig)
1151{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001152 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001153 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001154
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001155 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001156 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001157 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1158 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001159
1160 /* Not a signal, just exit */
1161 if (sig <= 0)
1162 _exit(- sig);
1163
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001164 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001165}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001166#else
1167
1168#define disable_restore_tty_pgrp_on_exit() ((void)0)
1169#define enable_restore_tty_pgrp_on_exit() ((void)0)
1170
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001171#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001172
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001173/* Restores tty foreground process group, and exits. */
1174static void hush_exit(int exitcode) NORETURN;
1175static void hush_exit(int exitcode)
1176{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001177 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1178 /* Prevent recursion:
1179 * trap "echo Hi; exit" EXIT; exit
1180 */
1181 char *argv[] = { NULL, G.traps[0], NULL };
1182 G.traps[0] = NULL;
1183 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001184 builtin_eval(argv);
1185 free(argv[1]);
1186 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001187
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001188#if ENABLE_HUSH_JOB
1189 fflush(NULL); /* flush all streams */
1190 sigexit(- (exitcode & 0xff));
1191#else
1192 exit(exitcode);
1193#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001194}
1195
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001196static int check_and_run_traps(int sig)
1197{
1198 static const struct timespec zero_timespec = { 0, 0 };
1199 smalluint save_rcode;
1200 int last_sig = 0;
1201
1202 if (sig)
1203 goto jump_in;
1204 while (1) {
1205 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1206 if (sig <= 0)
1207 break;
1208 jump_in:
1209 last_sig = sig;
1210 if (G.traps && G.traps[sig]) {
1211 if (G.traps[sig][0]) {
1212 /* We have user-defined handler */
1213 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1214 save_rcode = G.last_exitcode;
1215 builtin_eval(argv);
1216 free(argv[1]);
1217 G.last_exitcode = save_rcode;
1218 } /* else: "" trap, ignoring signal */
1219 continue;
1220 }
1221 /* not a trap: special action */
1222 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001223#if ENABLE_HUSH_FAST
1224 case SIGCHLD:
1225 G.count_SIGCHLD++;
1226//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1227 break;
1228#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001229 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001230 /* Builtin was ^C'ed, make it look prettier: */
1231 bb_putchar('\n');
1232 G.flag_SIGINT = 1;
1233 break;
1234#if ENABLE_HUSH_JOB
1235 case SIGHUP: {
1236 struct pipe *job;
1237 /* bash is observed to signal whole process groups,
1238 * not individual processes */
1239 for (job = G.job_list; job; job = job->next) {
1240 if (job->pgrp <= 0)
1241 continue;
1242 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1243 if (kill(- job->pgrp, SIGHUP) == 0)
1244 kill(- job->pgrp, SIGCONT);
1245 }
1246 sigexit(SIGHUP);
1247 }
1248#endif
1249 default: /* ignored: */
1250 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1251 break;
1252 }
1253 }
1254 return last_sig;
1255}
1256
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001257
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001258static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001259{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001260 if (force || G.cwd == NULL) {
1261 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1262 * we must not try to free(bb_msg_unknown) */
1263 if (G.cwd == bb_msg_unknown)
1264 G.cwd = NULL;
1265 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1266 if (!G.cwd)
1267 G.cwd = bb_msg_unknown;
1268 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001269 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001270}
1271
Denis Vlasenko83506862007-11-23 13:11:42 +00001272
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001273/*
1274 * Shell and environment variable support
1275 */
1276static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001277{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001278 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001279 struct variable *cur;
1280 int len;
1281
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001282 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001283 pp = &G.top_var;
1284 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001285 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001286 return pp;
1287 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001288 }
1289 return NULL;
1290}
1291
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001292static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001293{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001294 struct variable **pp = get_ptr_to_local_var(name);
1295 if (pp)
1296 return *pp;
1297 return NULL;
1298}
1299
1300static const char *get_local_var_value(const char *name)
1301{
1302 struct variable **pp = get_ptr_to_local_var(name);
1303 if (pp)
1304 return strchr((*pp)->varstr, '=') + 1;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001305 return NULL;
1306}
1307
1308/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001309 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001310 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001311 * 0: do not change export flag
1312 * (if creating new variable, flag will be 0)
1313 * 1: set export flag and putenv the variable
1314 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001315 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001316 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001317#if !BB_MMU && ENABLE_HUSH_LOCAL
1318/* all params are used */
1319#elif BB_MMU && ENABLE_HUSH_LOCAL
1320#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1321 set_local_var(str, flg_export, local_lvl)
1322#elif BB_MMU && !ENABLE_HUSH_LOCAL
1323#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001324 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001325#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1326#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1327 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001328#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001329static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001330{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001331 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001332 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001333 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001334 int name_len;
1335
Denis Vlasenko950bd722009-04-21 11:23:56 +00001336 eq_sign = strchr(str, '=');
1337 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001338 free(str);
1339 return -1;
1340 }
1341
Denis Vlasenko950bd722009-04-21 11:23:56 +00001342 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001343 var_pp = &G.top_var;
1344 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001345 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001346 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001347 continue;
1348 }
1349 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001350 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001351#if !BB_MMU
1352 if (!flg_read_only)
1353#endif
1354 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001355 free(str);
1356 return -1;
1357 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001358 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001359 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1360 *eq_sign = '\0';
1361 unsetenv(str);
1362 *eq_sign = '=';
1363 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001364#if ENABLE_HUSH_LOCAL
1365 if (cur->func_nest_level < local_lvl) {
1366 /* New variable is declared as local,
1367 * and existing one is global, or local
1368 * from enclosing function.
1369 * Remove and save old one: */
1370 *var_pp = cur->next;
1371 cur->next = *G.shadowed_vars_pp;
1372 *G.shadowed_vars_pp = cur;
1373 /* bash 3.2.33(1) and exported vars:
1374 * # export z=z
1375 * # f() { local z=a; env | grep ^z; }
1376 * # f
1377 * z=a
1378 * # env | grep ^z
1379 * z=z
1380 */
1381 if (cur->flg_export)
1382 flg_export = 1;
1383 break;
1384 }
1385#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001386 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001387 free_and_exp:
1388 free(str);
1389 goto exp;
1390 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001391 if (cur->max_len != 0) {
1392 if (cur->max_len >= strlen(str)) {
1393 /* This one is from startup env, reuse space */
1394 strcpy(cur->varstr, str);
1395 goto free_and_exp;
1396 }
1397 } else {
1398 /* max_len == 0 signifies "malloced" var, which we can
1399 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001400 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001401 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001402 cur->max_len = 0;
1403 goto set_str_and_exp;
1404 }
1405
Denys Vlasenko295fef82009-06-03 12:47:26 +02001406 /* Not found - create new variable struct */
1407 cur = xzalloc(sizeof(*cur));
1408#if ENABLE_HUSH_LOCAL
1409 cur->func_nest_level = local_lvl;
1410#endif
1411 cur->next = *var_pp;
1412 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001413
1414 set_str_and_exp:
1415 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001416#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001417 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001418#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001419 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001420 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001421 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001422 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1423 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001424 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001425 if (flg_export == -1) {
1426 cur->flg_export = 0;
1427 /* unsetenv was already done */
1428 } else {
1429 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1430 return putenv(cur->varstr);
1431 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001432 }
1433 return 0;
1434}
1435
Denys Vlasenko6db47842009-09-05 20:15:17 +02001436/* Used at startup and after each cd */
1437static void set_pwd_var(int exp)
1438{
1439 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1440 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1441}
1442
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001443static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001444{
1445 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001446 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001447
1448 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001449 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001450 var_pp = &G.top_var;
1451 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001452 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1453 if (cur->flg_read_only) {
1454 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001455 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001456 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001457 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001458 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1459 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001460 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1461 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001462 if (!cur->max_len)
1463 free(cur->varstr);
1464 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001465 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001466 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001467 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001468 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001469 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001470}
1471
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001472static int unset_local_var(const char *name)
1473{
1474 return unset_local_var_len(name, strlen(name));
1475}
1476
1477static void unset_vars(char **strings)
1478{
1479 char **v;
1480
1481 if (!strings)
1482 return;
1483 v = strings;
1484 while (*v) {
1485 const char *eq = strchrnul(*v, '=');
1486 unset_local_var_len(*v, (int)(eq - *v));
1487 v++;
1488 }
1489 free(strings);
1490}
1491
Mike Frysinger98c52642009-04-02 10:02:37 +00001492#if ENABLE_SH_MATH_SUPPORT
1493#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1494#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1495static char *endofname(const char *name)
1496{
1497 char *p;
1498
1499 p = (char *) name;
1500 if (!is_name(*p))
1501 return p;
1502 while (*++p) {
1503 if (!is_in_name(*p))
1504 break;
1505 }
1506 return p;
1507}
1508
1509static void arith_set_local_var(const char *name, const char *val, int flags)
1510{
1511 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001512 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001513 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001514}
1515#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001516
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001517
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001518/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001519 * Helpers for "var1=val1 var2=val2 cmd" feature
1520 */
1521static void add_vars(struct variable *var)
1522{
1523 struct variable *next;
1524
1525 while (var) {
1526 next = var->next;
1527 var->next = G.top_var;
1528 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001529 if (var->flg_export) {
1530 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001531 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001532 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001533 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001534 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001535 var = next;
1536 }
1537}
1538
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001539static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001540{
1541 char **s;
1542 struct variable *old = NULL;
1543
1544 if (!strings)
1545 return old;
1546 s = strings;
1547 while (*s) {
1548 struct variable *var_p;
1549 struct variable **var_pp;
1550 char *eq;
1551
1552 eq = strchr(*s, '=');
1553 if (eq) {
1554 *eq = '\0';
1555 var_pp = get_ptr_to_local_var(*s);
1556 *eq = '=';
1557 if (var_pp) {
1558 /* Remove variable from global linked list */
1559 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001560 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001561 *var_pp = var_p->next;
1562 /* Add it to returned list */
1563 var_p->next = old;
1564 old = var_p;
1565 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001566 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001567 }
1568 s++;
1569 }
1570 return old;
1571}
1572
1573
1574/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001575 * in_str support
1576 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001577static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001578{
1579 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001580 if (ch != '\0')
1581 return ch;
1582 i->p--;
1583 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001584}
1585
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001586static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001587{
1588 return *i->p;
1589}
1590
1591#if ENABLE_HUSH_INTERACTIVE
1592
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001593static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001594{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001595 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001596 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001597 if (G.PS1 == NULL)
1598 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001599 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001600 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001601 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001602 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001603 if (G.PS2 == NULL)
1604 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001605}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001606
1607static const char* setup_prompt_string(int promptmode)
1608{
1609 const char *prompt_str;
1610 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001611 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1612 /* Set up the prompt */
1613 if (promptmode == 0) { /* PS1 */
1614 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001615 /* bash uses $PWD value, even if it is set by user.
1616 * It uses current dir only if PWD is unset.
1617 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001618 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001619 prompt_str = G.PS1;
1620 } else
1621 prompt_str = G.PS2;
1622 } else
1623 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001624 debug_printf("result '%s'\n", prompt_str);
1625 return prompt_str;
1626}
1627
1628static void get_user_input(struct in_str *i)
1629{
1630 int r;
1631 const char *prompt_str;
1632
1633 prompt_str = setup_prompt_string(i->promptmode);
1634#if ENABLE_FEATURE_EDITING
1635 /* Enable command line editing only while a command line
1636 * is actually being read */
1637 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001638 G.flag_SIGINT = 0;
1639 /* buglet: SIGINT will not make new prompt to appear _at once_,
1640 * only after <Enter>. (^C will work) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001641 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001642 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001643 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001644 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001645 i->eof_flag = (r < 0);
1646 if (i->eof_flag) { /* EOF/error detected */
1647 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1648 G.user_input_buf[1] = '\0';
1649 }
1650#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001651 do {
1652 G.flag_SIGINT = 0;
1653 fputs(prompt_str, stdout);
1654 fflush(stdout);
1655 G.user_input_buf[0] = r = fgetc(i->file);
1656 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001657//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001658 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001659 i->eof_flag = (r == EOF);
1660#endif
1661 i->p = G.user_input_buf;
1662}
1663
1664#endif /* INTERACTIVE */
1665
1666/* This is the magic location that prints prompts
1667 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001668static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001669{
1670 int ch;
1671
1672 /* If there is data waiting, eat it up */
1673 if (i->p && *i->p) {
1674#if ENABLE_HUSH_INTERACTIVE
1675 take_cached:
1676#endif
1677 ch = *i->p++;
1678 if (i->eof_flag && !*i->p)
1679 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001680 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001681 } else {
1682 /* need to double check i->file because we might be doing something
1683 * more complicated by now, like sourcing or substituting. */
1684#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001685 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001686 do {
1687 get_user_input(i);
1688 } while (!*i->p); /* need non-empty line */
1689 i->promptmode = 1; /* PS2 */
1690 i->promptme = 0;
1691 goto take_cached;
1692 }
1693#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001694 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001695 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001696 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001697#if ENABLE_HUSH_INTERACTIVE
1698 if (ch == '\n')
1699 i->promptme = 1;
1700#endif
1701 return ch;
1702}
1703
Denis Vlasenko913a2012009-04-05 22:17:04 +00001704/* All callers guarantee this routine will never
1705 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001706 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001707static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001708{
1709 int ch;
1710 if (i->p && *i->p) {
1711 if (i->eof_flag && !i->p[1])
1712 return EOF;
1713 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001714 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001715 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001716 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001717 i->eof_flag = (ch == EOF);
1718 i->peek_buf[0] = ch;
1719 i->peek_buf[1] = '\0';
1720 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001721 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001722 return ch;
1723}
1724
1725static void setup_file_in_str(struct in_str *i, FILE *f)
1726{
1727 i->peek = file_peek;
1728 i->get = file_get;
1729#if ENABLE_HUSH_INTERACTIVE
1730 i->promptme = 1;
1731 i->promptmode = 0; /* PS1 */
1732#endif
1733 i->file = f;
1734 i->p = NULL;
1735}
1736
1737static void setup_string_in_str(struct in_str *i, const char *s)
1738{
1739 i->peek = static_peek;
1740 i->get = static_get;
1741#if ENABLE_HUSH_INTERACTIVE
1742 i->promptme = 1;
1743 i->promptmode = 0; /* PS1 */
1744#endif
1745 i->p = s;
1746 i->eof_flag = 0;
1747}
1748
1749
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001750/*
1751 * o_string support
1752 */
1753#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001754
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001755static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001756{
1757 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001758 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001759 if (o->data)
1760 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001761}
1762
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001763static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001764{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001765 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001766 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001767}
1768
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001769static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1770{
1771 free(o->data);
1772}
1773
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001774static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001775{
1776 if (o->length + len > o->maxlen) {
1777 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1778 o->data = xrealloc(o->data, 1 + o->maxlen);
1779 }
1780}
1781
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001782static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001783{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001784 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1785 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001786 o->data[o->length] = ch;
1787 o->length++;
1788 o->data[o->length] = '\0';
1789}
1790
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001791static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001792{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001793 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001794 memcpy(&o->data[o->length], str, len);
1795 o->length += len;
1796 o->data[o->length] = '\0';
1797}
1798
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001799#if !BB_MMU
1800static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001801{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001802 o_addblock(o, str, strlen(str));
1803}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001804static void nommu_addchr(o_string *o, int ch)
1805{
1806 if (o)
1807 o_addchr(o, ch);
1808}
1809#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001810# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001811#endif
1812
1813static void o_addstr_with_NUL(o_string *o, const char *str)
1814{
1815 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001816}
1817
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001818static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001819{
1820 while (len) {
1821 o_addchr(o, *str);
1822 if (*str++ == '\\'
1823 && (*str != '*' && *str != '?' && *str != '[')
1824 ) {
1825 o_addchr(o, '\\');
1826 }
1827 len--;
1828 }
1829}
1830
Eric Andersen25f27032001-04-26 23:22:31 +00001831/* My analysis of quoting semantics tells me that state information
1832 * is associated with a destination, not a source.
1833 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001834static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001835{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001836 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001837 char *found = strchr("*?[\\", ch);
1838 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001839 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001840 o_grow_by(o, sz);
1841 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001842 o->data[o->length] = '\\';
1843 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001844 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001845 o->data[o->length] = ch;
1846 o->length++;
1847 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001848}
1849
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001850static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001851{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001852 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001853 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001854 sz++;
1855 o->data[o->length] = '\\';
1856 o->length++;
1857 }
1858 o_grow_by(o, sz);
1859 o->data[o->length] = ch;
1860 o->length++;
1861 o->data[o->length] = '\0';
1862}
1863
1864static void o_addQstr(o_string *o, const char *str, int len)
1865{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001866 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001867 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001868 return;
1869 }
1870 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001871 char ch;
1872 int sz;
1873 int ordinary_cnt = strcspn(str, "*?[\\");
1874 if (ordinary_cnt > len) /* paranoia */
1875 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001876 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001877 if (ordinary_cnt == len)
1878 return;
1879 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001880 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001881
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001882 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001883 sz = 1;
1884 if (ch) { /* it is necessarily one of "*?[\\" */
1885 sz++;
1886 o->data[o->length] = '\\';
1887 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001888 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001889 o_grow_by(o, sz);
1890 o->data[o->length] = ch;
1891 o->length++;
1892 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001893 }
1894}
1895
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001896/* A special kind of o_string for $VAR and `cmd` expansion.
1897 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001898 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001899 * list[i] contains an INDEX (int!) into this string data.
1900 * It means that if list[] needs to grow, data needs to be moved higher up
1901 * but list[i]'s need not be modified.
1902 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001903 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001904 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1905 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001906#if DEBUG_EXPAND || DEBUG_GLOB
1907static void debug_print_list(const char *prefix, o_string *o, int n)
1908{
1909 char **list = (char**)o->data;
1910 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1911 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001912
1913 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001914 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1915 prefix, list, n, string_start, o->length, o->maxlen);
1916 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001917 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001918 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1919 o->data + (int)list[i] + string_start,
1920 o->data + (int)list[i] + string_start);
1921 i++;
1922 }
1923 if (n) {
1924 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001925 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001926 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001927 }
1928}
1929#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001930# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001931#endif
1932
1933/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1934 * in list[n] so that it points past last stored byte so far.
1935 * It returns n+1. */
1936static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001937{
1938 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001939 int string_start;
1940 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001941
1942 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001943 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1944 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001945 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001946 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001947 /* list[n] points to string_start, make space for 16 more pointers */
1948 o->maxlen += 0x10 * sizeof(list[0]);
1949 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001950 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001951 memmove(list + n + 0x10, list + n, string_len);
1952 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001953 } else {
1954 debug_printf_list("list[%d]=%d string_start=%d\n",
1955 n, string_len, string_start);
1956 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001957 } else {
1958 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001959 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1960 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001961 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1962 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001963 o->has_empty_slot = 0;
1964 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001965 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001966 return n + 1;
1967}
1968
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001969/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001970static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001971{
1972 char **list = (char**)o->data;
1973 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1974
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001975 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001976}
1977
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001978/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001979 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001980static int o_glob(o_string *o, int n)
1981{
1982 glob_t globdata;
1983 int gr;
1984 char *pattern;
1985
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001986 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001987 if (!o->data)
1988 return o_save_ptr_helper(o, n);
1989 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001990 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001991 if (!glob_needed(pattern)) {
1992 literal:
1993 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001994 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001995 return o_save_ptr_helper(o, n);
1996 }
1997
1998 memset(&globdata, 0, sizeof(globdata));
1999 gr = glob(pattern, 0, NULL, &globdata);
2000 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2001 if (gr == GLOB_NOSPACE)
2002 bb_error_msg_and_die("out of memory during glob");
2003 if (gr == GLOB_NOMATCH) {
2004 globfree(&globdata);
2005 goto literal;
2006 }
2007 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002008 /* TODO: testcase for bad glob pattern behavior */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002009 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2010 }
2011 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2012 char **argv = globdata.gl_pathv;
2013 o->length = pattern - o->data; /* "forget" pattern */
2014 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002015 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002016 n = o_save_ptr_helper(o, n);
2017 argv++;
2018 if (!*argv)
2019 break;
2020 }
2021 }
2022 globfree(&globdata);
2023 if (DEBUG_GLOB)
2024 debug_print_list("o_glob returning", o, n);
2025 return n;
2026}
2027
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002028/* If o->o_glob == 1, glob the string so far remembered.
2029 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002030static int o_save_ptr(o_string *o, int n)
2031{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002032 if (o->o_glob) { /* if globbing is requested */
2033 /* If o->has_empty_slot, list[n] was already globbed
2034 * (if it was requested back then when it was filled)
2035 * so don't do that again! */
2036 if (!o->has_empty_slot)
2037 return o_glob(o, n); /* o_save_ptr_helper is inside */
2038 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002039 return o_save_ptr_helper(o, n);
2040}
2041
2042/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002043static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002044{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002045 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002046 int string_start;
2047
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002048 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2049 if (DEBUG_EXPAND)
2050 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002051 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002052 list = (char**)o->data;
2053 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2054 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002055 while (n) {
2056 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002057 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002058 }
2059 return list;
2060}
2061
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002062
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002063/* Expansion can recurse */
2064#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002065static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002066#endif
2067static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002068#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002069#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002070 parse_stream_dquoted(dest, input, dquote_end)
2071#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002072static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002073 o_string *dest,
2074 struct in_str *input,
2075 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002076
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002077/* expand_strvec_to_strvec() takes a list of strings, expands
2078 * all variable references within and returns a pointer to
2079 * a list of expanded strings, possibly with larger number
2080 * of strings. (Think VAR="a b"; echo $VAR).
2081 * This new list is allocated as a single malloc block.
2082 * NULL-terminated list of char* pointers is at the beginning of it,
2083 * followed by strings themself.
2084 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002085
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002086/* Store given string, finalizing the word and starting new one whenever
2087 * we encounter IFS char(s). This is used for expanding variable values.
2088 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2089static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002090{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002091 while (1) {
2092 int word_len = strcspn(str, G.ifs);
2093 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002094 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002095 o_addQstr(output, str, word_len);
2096 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002097 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002098 str += word_len;
2099 }
2100 if (!*str) /* EOL - do not finalize word */
2101 break;
2102 o_addchr(output, '\0');
2103 debug_print_list("expand_on_ifs", output, n);
2104 n = o_save_ptr(output, n);
2105 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002106 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002107 debug_print_list("expand_on_ifs[1]", output, n);
2108 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002109}
2110
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002111/* Helper to expand $((...)) and heredoc body. These act as if
2112 * they are in double quotes, with the exception that they are not :).
2113 * Just the rules are similar: "expand only $var and `cmd`"
2114 *
2115 * Returns malloced string.
2116 * As an optimization, we return NULL if expansion is not needed.
2117 */
2118static char *expand_pseudo_dquoted(const char *str)
2119{
2120 char *exp_str;
2121 struct in_str input;
2122 o_string dest = NULL_O_STRING;
2123
2124 if (strchr(str, '$') == NULL
2125#if ENABLE_HUSH_TICK
2126 && strchr(str, '`') == NULL
2127#endif
2128 ) {
2129 return NULL;
2130 }
2131
2132 /* We need to expand. Example:
2133 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2134 */
2135 setup_string_in_str(&input, str);
2136 parse_stream_dquoted(NULL, &dest, &input, EOF);
2137 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2138 exp_str = expand_string_to_string(dest.data);
2139 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2140 o_free_unsafe(&dest);
2141 return exp_str;
2142}
2143
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002144/* Expand all variable references in given string, adding words to list[]
2145 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2146 * to be filled). This routine is extremely tricky: has to deal with
2147 * variables/parameters with whitespace, $* and $@, and constructs like
2148 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2149static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002150{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002151 /* or_mask is either 0 (normal case) or 0x80 -
2152 * expansion of right-hand side of assignment == 1-element expand.
2153 * It will also do no globbing, and thus we must not backslash-quote!
2154 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002155 char ored_ch;
2156 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002157
2158 ored_ch = 0;
2159
2160 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2161 debug_print_list("expand_vars_to_list", output, n);
2162 n = o_save_ptr(output, n);
2163 debug_print_list("expand_vars_to_list[0]", output, n);
2164
2165 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002166 char first_ch;
2167 int i;
2168 char *dyn_val = NULL;
2169 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002170#if ENABLE_HUSH_TICK
2171 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002172#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002173#if ENABLE_SH_MATH_SUPPORT
2174 char arith_buf[sizeof(arith_t)*3 + 2];
2175#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002176 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002177 debug_print_list("expand_vars_to_list[1]", output, n);
2178 arg = ++p;
2179 p = strchr(p, SPECIAL_VAR_SYMBOL);
2180
2181 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2182 /* "$@" is special. Even if quoted, it can still
2183 * expand to nothing (not even an empty string) */
2184 if ((first_ch & 0x7f) != '@')
2185 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002186
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002187 switch (first_ch & 0x7f) {
2188 /* Highest bit in first_ch indicates that var is double-quoted */
2189 case '$': /* pid */
2190 val = utoa(G.root_pid);
2191 break;
2192 case '!': /* bg pid */
2193 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2194 break;
2195 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002196 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002197 break;
2198 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002199 if (arg[1] != SPECIAL_VAR_SYMBOL)
2200 /* actually, it's a ${#var} */
2201 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2203 break;
2204 case '*':
2205 case '@':
2206 i = 1;
2207 if (!G.global_argv[i])
2208 break;
2209 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2210 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002211 smallint sv = output->o_escape;
2212 /* unquoted var's contents should be globbed, so don't escape */
2213 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002214 while (G.global_argv[i]) {
2215 n = expand_on_ifs(output, n, G.global_argv[i]);
2216 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2217 if (G.global_argv[i++][0] && G.global_argv[i]) {
2218 /* this argv[] is not empty and not last:
2219 * put terminating NUL, start new word */
2220 o_addchr(output, '\0');
2221 debug_print_list("expand_vars_to_list[2]", output, n);
2222 n = o_save_ptr(output, n);
2223 debug_print_list("expand_vars_to_list[3]", output, n);
2224 }
2225 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002226 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002227 } else
2228 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2229 * and in this case should treat it like '$*' - see 'else...' below */
2230 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2231 while (1) {
2232 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2233 if (++i >= G.global_argc)
2234 break;
2235 o_addchr(output, '\0');
2236 debug_print_list("expand_vars_to_list[4]", output, n);
2237 n = o_save_ptr(output, n);
2238 }
2239 } else { /* quoted $*: add as one word */
2240 while (1) {
2241 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2242 if (!G.global_argv[++i])
2243 break;
2244 if (G.ifs[0])
2245 o_addchr(output, G.ifs[0]);
2246 }
2247 }
2248 break;
2249 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2250 /* "Empty variable", used to make "" etc to not disappear */
2251 arg++;
2252 ored_ch = 0x80;
2253 break;
2254#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002255 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002256 *p = '\0';
2257 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002258 /* Can't just stuff it into output o_string,
2259 * expanded result may need to be globbed
2260 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002261 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002262 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002263 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2264 val = subst_result.data;
2265 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002266#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002267#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002268 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002269 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002270 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002271 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002272 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002273
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002274 arg++; /* skip '+' */
2275 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002276 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002277
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002278 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002279 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002280 hooks.setvar = arith_set_local_var;
2281 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002282 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2283 free(exp_str);
2284
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002285 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002286 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002287 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002288 case -3:
2289 msg = "exponent less than 0";
2290 break;
2291 case -2:
2292 msg = "divide by 0";
2293 break;
2294 case -5:
2295 msg = "expression recursion loop detected";
2296 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002297 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002298 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002299 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002300 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002301 sprintf(arith_buf, arith_t_fmt, res);
2302 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002303 break;
2304 }
2305#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002306 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002307 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002308 bool exp_len = false;
2309 bool exp_null = false;
2310 char *var = arg;
2311 char exp_save = exp_save; /* for compiler */
2312 char exp_op = exp_op; /* for compiler */
2313 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002314 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002315
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002316 *p = '\0';
2317 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002318
2319 /* prepare for expansions */
2320 if (var[0] == '#') {
2321 /* handle length expansion ${#var} */
2322 exp_len = true;
2323 ++var;
2324 } else {
2325 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002326 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002327 if (!var[exp_off])
2328 exp_off = 0;
2329 if (exp_off) {
2330 exp_save = var[exp_off];
2331 exp_null = exp_save == ':';
2332 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002333 if (exp_null)
2334 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002335 exp_op = *exp_word++;
2336 var[exp_off] = '\0';
2337 }
2338 }
2339
2340 /* lookup the variable in question */
2341 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002342 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002343 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002344 if (i < G.global_argc)
2345 val = G.global_argv[i];
2346 /* else val remains NULL: $N with too big N */
2347 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002348 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002349
2350 /* handle any expansions */
2351 if (exp_len) {
2352 debug_printf_expand("expand: length of '%s' = ", val);
2353 val = utoa(val ? strlen(val) : 0);
2354 debug_printf_expand("%s\n", val);
2355 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002356 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002357 if (val) {
2358 /* we need to do a pattern match */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002359 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002360 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002361 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002362 if (exp_op == *exp_word) /* ## or %% */
2363 ++exp_word;
2364 val = dyn_val = xstrdup(val);
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002365 loc = scan(dyn_val, exp_word, match_at_left);
2366 if (match_at_left) /* # or ## */
Mike Frysinger57e74672009-04-09 23:00:33 +00002367 val = loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002368 else if (loc) /* % or %% and match was found */
Mike Frysinger57e74672009-04-09 23:00:33 +00002369 *loc = '\0';
2370 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002371 } else {
2372 /* we need to do an expansion */
2373 int exp_test = (!val || (exp_null && !val[0]));
2374 if (exp_op == '+')
2375 exp_test = !exp_test;
2376 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2377 exp_null ? "true" : "false", exp_test);
2378 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002379 if (exp_op == '?') {
2380//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002381 /* ${var?[error_msg_if_unset]} */
2382 /* ${var:?[error_msg_if_unset_or_null]} */
2383 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002384 die_if_script("%s: %s",
2385 var,
2386 exp_word[0] ? exp_word : "parameter null or not set"
2387 );
2388 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002389 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002390 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002391
Mike Frysingera4f331d2009-04-07 06:03:22 +00002392 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002393 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002394 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002395 /* mimic bash message */
2396 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002397 val = NULL;
2398 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002399 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002400 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002401 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002402 }
2403 }
2404 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002405
Mike Frysinger6379bb42009-03-28 18:55:03 +00002406 var[exp_off] = exp_save;
2407 }
2408
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002409 arg[0] = first_ch;
2410#if ENABLE_HUSH_TICK
2411 store_val:
2412#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002413 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002414 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002415 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002416 /* unquoted var's contents should be globbed, so don't escape */
2417 smallint sv = output->o_escape;
2418 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002419 n = expand_on_ifs(output, n, val);
2420 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002421 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002422 }
2423 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002424 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002425 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002426 } /* default: */
2427 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002428
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002429 if (val) {
2430 o_addQstr(output, val, strlen(val));
2431 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002432 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002433 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002434 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002435 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002436
2437#if ENABLE_HUSH_TICK
2438 o_free(&subst_result);
2439#endif
2440 arg = ++p;
2441 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2442
2443 if (arg[0]) {
2444 debug_print_list("expand_vars_to_list[a]", output, n);
2445 /* this part is literal, and it was already pre-quoted
2446 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002447 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002448 debug_print_list("expand_vars_to_list[b]", output, n);
2449 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2450 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2451 ) {
2452 n--;
2453 /* allow to reuse list[n] later without re-growth */
2454 output->has_empty_slot = 1;
2455 } else {
2456 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002457 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002458 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002459}
2460
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002461static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002462{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002463 int n;
2464 char **list;
2465 char **v;
2466 o_string output = NULL_O_STRING;
2467
2468 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002469 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002470 /* (unquoted $var will temporarily switch it off) */
2471 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002472 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002473
2474 n = 0;
2475 v = argv;
2476 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002477 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002478 v++;
2479 }
2480 debug_print_list("expand_variables", &output, n);
2481
2482 /* output.data (malloced in one block) gets returned in "list" */
2483 list = o_finalize_list(&output, n);
2484 debug_print_strings("expand_variables[1]", list);
2485 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002486}
2487
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002488static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002489{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002490 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002491}
2492
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002493#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002494static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2495{
2496 return expand_variables(argv, 0x80);
2497}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002498#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002499
2500#ifdef CMD_SINGLEWORD_NOGLOB_COND
2501static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2502{
2503 int n;
2504 char **list;
2505 char **v;
2506 o_string output = NULL_O_STRING;
2507
2508 n = 0;
2509 v = argv;
2510 while (*v) {
2511 int is_var = is_well_formed_var_name(*v, '=');
2512 /* is_var * 0x80: singleword expansion for vars */
2513 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2514
2515 /* Subtle! expand_vars_to_list did not glob last word yet.
2516 * It does this only when fed with further data.
2517 * Therefore we set globbing flags AFTER it, not before:
2518 */
2519
2520 /* if it is not recognizably abc=...; then: */
2521 output.o_escape = !is_var; /* protect against globbing for "$var" */
2522 /* (unquoted $var will temporarily switch it off) */
2523 output.o_glob = !is_var; /* and indeed do globbing */
2524 v++;
2525 }
2526 debug_print_list("expand_cond", &output, n);
2527
2528 /* output.data (malloced in one block) gets returned in "list" */
2529 list = o_finalize_list(&output, n);
2530 debug_print_strings("expand_cond[1]", list);
2531 return list;
2532}
2533#endif
2534
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002535/* Used for expansion of right hand of assignments */
2536/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2537 * "v=/bin/c*" */
2538static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002539{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002540 char *argv[2], **list;
2541
2542 argv[0] = (char*)str;
2543 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002544 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002545 if (HUSH_DEBUG)
2546 if (!list[0] || list[1])
2547 bb_error_msg_and_die("BUG in varexp2");
2548 /* actually, just move string 2*sizeof(char*) bytes back */
2549 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002550 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002551 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2552 return (char*)list;
2553}
2554
2555/* Used for "eval" builtin */
2556static char* expand_strvec_to_string(char **argv)
2557{
2558 char **list;
2559
2560 list = expand_variables(argv, 0x80);
2561 /* Convert all NULs to spaces */
2562 if (list[0]) {
2563 int n = 1;
2564 while (list[n]) {
2565 if (HUSH_DEBUG)
2566 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2567 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002568 /* bash uses ' ' regardless of $IFS contents */
2569 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002570 n++;
2571 }
2572 }
2573 overlapping_strcpy((char*)list, list[0]);
2574 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2575 return (char*)list;
2576}
2577
2578static char **expand_assignments(char **argv, int count)
2579{
2580 int i;
2581 char **p = NULL;
2582 /* Expand assignments into one string each */
2583 for (i = 0; i < count; i++) {
2584 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2585 }
2586 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002587}
2588
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002589
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002590#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002591/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002592void re_execute_shell(char ***to_free, const char *s,
2593 char *g_argv0, char **g_argv,
2594 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002595
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002596static void reset_traps_to_defaults(void)
2597{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002598 /* This function is always called in a child shell
2599 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002600 * Child shells are not interactive.
2601 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2602 * Testcase: (while :; do :; done) + ^Z should background.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002603 * Same goes for SIGTERM, SIGHUP, SIGINT.
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002604 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002605 unsigned sig;
2606 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002607
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002608 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2609 return;
2610
2611 /* Stupid. It can be done with *single* &= op, but we can't use
2612 * the fact that G.blocked_set is implemented as a bitmask... */
2613 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2614 sig = 1;
2615 while (1) {
2616 if (mask & 1)
2617 sigdelset(&G.blocked_set, sig);
2618 mask >>= 1;
2619 if (!mask)
2620 break;
2621 sig++;
2622 }
2623
2624 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2625 mask = G.non_DFL_mask;
2626 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2627 if (!G.traps[sig])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002628 continue;
2629 free(G.traps[sig]);
2630 G.traps[sig] = NULL;
2631 /* There is no signal for 0 (EXIT) */
2632 if (sig == 0)
2633 continue;
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002634 /* There was a trap handler, we are removing it.
2635 * But if sig still has non-DFL handling,
2636 * we should not unblock it. */
2637 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002638 continue;
2639 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002640 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002641 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002642}
2643
2644#else /* !BB_MMU */
2645
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002646static void re_execute_shell(char ***to_free, const char *s,
2647 char *g_argv0, char **g_argv,
2648 char **builtin_argv) NORETURN;
2649static void re_execute_shell(char ***to_free, const char *s,
2650 char *g_argv0, char **g_argv,
2651 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002652{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002653 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002654 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002655 struct variable *cur;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002656#if ENABLE_HUSH_FUNCTIONS
2657 struct function *funcp;
2658#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002659 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002660 unsigned cnt;
2661
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002662 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002663 argv = heredoc_argv;
2664 argv[0] = (char *) G.argv0_for_re_execing;
2665 argv[1] = (char *) "-<";
2666 argv[2] = (char *) s;
2667 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002668 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002669 goto do_exec;
2670 }
2671
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002672 cnt = 0;
2673 pp = builtin_argv;
2674 if (pp) while (*pp++)
2675 cnt++;
2676
2677 sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002678 , (unsigned) G.root_pid
2679 , (unsigned) G.last_bg_pid
2680 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002681 , cnt
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002682 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002683 );
Denis Vlasenkobc569742009-04-12 20:35:19 +00002684 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002685 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002686 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002687 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002688 for (cur = G.top_var; cur; cur = cur->next) {
2689 if (!cur->flg_export || cur->flg_read_only)
2690 cnt += 2;
2691 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002692#if ENABLE_HUSH_FUNCTIONS
2693 for (funcp = G.top_func; funcp; funcp = funcp->next)
2694 cnt += 3;
2695#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002696 pp = g_argv;
2697 while (*pp++)
2698 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002699 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002700 *pp++ = (char *) G.argv0_for_re_execing;
2701 *pp++ = param_buf;
2702 for (cur = G.top_var; cur; cur = cur->next) {
2703 if (cur->varstr == hush_version_str)
2704 continue;
2705 if (cur->flg_read_only) {
2706 *pp++ = (char *) "-R";
2707 *pp++ = cur->varstr;
2708 } else if (!cur->flg_export) {
2709 *pp++ = (char *) "-V";
2710 *pp++ = cur->varstr;
2711 }
2712 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002713#if ENABLE_HUSH_FUNCTIONS
2714 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2715 *pp++ = (char *) "-F";
2716 *pp++ = funcp->name;
2717 *pp++ = funcp->body_as_string;
2718 }
2719#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002720 /* We can pass activated traps here. Say, -Tnn:trap_string
2721 *
2722 * However, POSIX says that subshells reset signals with traps
2723 * to SIG_DFL.
2724 * I tested bash-3.2 and it not only does that with true subshells
2725 * of the form ( list ), but with any forked children shells.
2726 * I set trap "echo W" WINCH; and then tried:
2727 *
2728 * { echo 1; sleep 20; echo 2; } &
2729 * while true; do echo 1; sleep 20; echo 2; break; done &
2730 * true | { echo 1; sleep 20; echo 2; } | cat
2731 *
2732 * In all these cases sending SIGWINCH to the child shell
2733 * did not run the trap. If I add trap "echo V" WINCH;
2734 * _inside_ group (just before echo 1), it works.
2735 *
2736 * I conclude it means we don't need to pass active traps here.
2737 * exec syscall below resets them to SIG_DFL for us.
2738 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002739 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002740 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002741 if (builtin_argv) {
2742 while (*++builtin_argv)
2743 *pp++ = *builtin_argv;
2744 *pp++ = (char *) "";
2745 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002746 *pp++ = g_argv0;
2747 while (*g_argv)
2748 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002749 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002750 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002751
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002752 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002753 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2754 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002755 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002756 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002757 if (argv[0][0] == '/')
2758 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002759 xfunc_error_retval = 127;
2760 bb_error_msg_and_die("can't re-execute the shell");
2761}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002762#endif /* !BB_MMU */
2763
2764
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002765static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002766{
2767 struct fd_pair pair;
2768 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002769 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002770 /* the _body_ of heredoc (misleading field name) */
2771 const char *heredoc = redir->rd_filename;
2772 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002773#if !BB_MMU
2774 char **to_free;
2775#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002776
2777 expanded = NULL;
2778 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2779 expanded = expand_pseudo_dquoted(heredoc);
2780 if (expanded)
2781 heredoc = expanded;
2782 }
2783 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002784
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002785 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002786 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002787 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002788
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002789 /* Try writing without forking. Newer kernels have
2790 * dynamically growing pipes. Must use non-blocking write! */
2791 ndelay_on(pair.wr);
2792 while (1) {
2793 written = write(pair.wr, heredoc, len);
2794 if (written <= 0)
2795 break;
2796 len -= written;
2797 if (len == 0) {
2798 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002799 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002800 return;
2801 }
2802 heredoc += written;
2803 }
2804 ndelay_off(pair.wr);
2805
2806 /* Okay, pipe buffer was not big enough */
2807 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002808 * for the unsuspecting parent process. Child creates a grandchild
2809 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002810 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002811#if !BB_MMU
2812 to_free = NULL;
2813#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002814 pid = vfork();
2815 if (pid < 0)
2816 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002817 if (pid == 0) {
2818 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002819 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002820 pid = BB_MMU ? fork() : vfork();
2821 if (pid < 0)
2822 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2823 if (pid != 0)
2824 _exit(0);
2825 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002826 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002827#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002828 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002829 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002830#else
2831 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002832 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002833 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002834#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002835 }
2836 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02002837#if ENABLE_HUSH_FAST
2838 G.count_SIGCHLD++;
2839//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2840#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002841 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002842#if !BB_MMU
2843 free(to_free);
2844#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002845 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002846 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002847 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002848}
2849
Eric Andersen25f27032001-04-26 23:22:31 +00002850/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2851 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002852static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002853{
2854 int openfd, mode;
2855 struct redir_struct *redir;
2856
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002857 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002858 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002859 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02002860 if (squirrel && redir->rd_fd < 3
2861 && squirrel[redir->rd_fd] < 0
2862 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002863 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002864 }
2865 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2866 * of the heredoc */
2867 debug_printf_parse("set heredoc '%s'\n",
2868 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002869 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00002870 continue;
2871 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002872
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002873 if (redir->rd_dup == REDIRFD_TO_FILE) {
2874 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002875 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002876 if (redir->rd_filename == NULL) {
2877 /* Something went wrong in the parse.
2878 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002879 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002880 continue;
2881 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002882 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002883 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002884 openfd = open_or_warn(p, mode);
2885 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002886 if (openfd < 0) {
2887 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002888 * bash and ash both lose it as well (though zsh doesn't!) */
2889//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00002890 return 1;
2891 }
2892 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002893 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002894 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00002895 }
2896
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002897 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02002898 if (squirrel && redir->rd_fd < 3
2899 && squirrel[redir->rd_fd] < 0
2900 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002901 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00002902 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002903 if (openfd == REDIRFD_CLOSE) {
2904 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002905 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002906 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002907 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002908 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002909 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002910 }
Eric Andersen25f27032001-04-26 23:22:31 +00002911 }
2912 }
2913 return 0;
2914}
2915
2916static void restore_redirects(int squirrel[])
2917{
2918 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002919 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002920 fd = squirrel[i];
2921 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002922 /* We simply die on error */
2923 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002924 }
2925 }
2926}
2927
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002928
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002929static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002930
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002931/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002932static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002933{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002934 char **p;
2935 struct command *command;
2936 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002937 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002938
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002939 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002940 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002941 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002942 for (i = 0; i < pi->num_cmds; i++) {
2943 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002944 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002945 if (command->argv) {
2946 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002947 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002948 }
2949 free_strings(command->argv);
2950 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002951 }
2952 /* not "else if": on syntax error, we may have both! */
2953 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002954 debug_printf_clean(" begin group (cmd_type:%d)\n",
2955 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002956 free_pipe_list(command->group);
2957 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002958 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002959 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002960 /* else is crucial here.
2961 * If group != NULL, child_func is meaningless */
2962#if ENABLE_HUSH_FUNCTIONS
2963 else if (command->child_func) {
2964 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2965 command->child_func->parent_cmd = NULL;
2966 }
2967#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002968#if !BB_MMU
2969 free(command->group_as_string);
2970 command->group_as_string = NULL;
2971#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002972 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002973 debug_printf_clean(" redirect %d%s",
2974 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002975 /* guard against the case >$FOO, where foo is unset or blank */
2976 if (r->rd_filename) {
2977 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2978 free(r->rd_filename);
2979 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002980 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002981 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002982 rnext = r->next;
2983 free(r);
2984 }
2985 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002986 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002987 free(pi->cmds); /* children are an array, they get freed all at once */
2988 pi->cmds = NULL;
2989#if ENABLE_HUSH_JOB
2990 free(pi->cmdtext);
2991 pi->cmdtext = NULL;
2992#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002993}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002994
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002995static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002996{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002997 struct pipe *pi, *next;
2998
2999 for (pi = head; pi; pi = next) {
3000#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003001 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003002#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003003 free_pipe(pi);
3004 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003005 next = pi->next;
3006 /*pi->next = NULL;*/
3007 free(pi);
3008 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003009}
3010
3011
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003012static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003013#if BB_MMU
3014#define parse_stream(pstring, input, end_trigger) \
3015 parse_stream(input, end_trigger)
3016#endif
3017static struct pipe *parse_stream(char **pstring,
3018 struct in_str *input,
3019 int end_trigger);
3020static void parse_and_run_string(const char *s);
3021
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003022
Mike Frysinger93cadc22009-05-27 17:06:25 -04003023static char *find_in_path(const char *arg)
3024{
3025 char *ret = NULL;
3026 const char *PATH = get_local_var_value("PATH");
3027
3028 if (!PATH)
3029 return NULL;
3030
3031 while (1) {
3032 const char *end = strchrnul(PATH, ':');
3033 int sz = end - PATH; /* must be int! */
3034
3035 free(ret);
3036 if (sz != 0) {
3037 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3038 } else {
3039 /* We have xxx::yyyy in $PATH,
3040 * it means "use current dir" */
3041 ret = xstrdup(arg);
3042 }
3043 if (access(ret, F_OK) == 0)
3044 break;
3045
3046 if (*end == '\0') {
3047 free(ret);
3048 return NULL;
3049 }
3050 PATH = end + 1;
3051 }
3052
3053 return ret;
3054}
3055
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003056static const struct built_in_command* find_builtin_helper(const char *name,
3057 const struct built_in_command *x,
3058 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003059{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003060 while (x != end) {
3061 if (strcmp(name, x->cmd) != 0) {
3062 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003063 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003064 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003065 debug_printf_exec("found builtin '%s'\n", name);
3066 return x;
3067 }
3068 return NULL;
3069}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003070static const struct built_in_command* find_builtin1(const char *name)
3071{
3072 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3073}
3074static const struct built_in_command* find_builtin(const char *name)
3075{
3076 const struct built_in_command *x = find_builtin1(name);
3077 if (x)
3078 return x;
3079 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3080}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003081
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003082#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003083static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003084{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003085 struct function **funcpp = &G.top_func;
3086 while (*funcpp) {
3087 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003088 break;
3089 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003090 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003091 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003092 return funcpp;
3093}
3094
3095static const struct function *find_function(const char *name)
3096{
3097 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003098 if (funcp)
3099 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003100 return funcp;
3101}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003102
Denis Vlasenkobc569742009-04-12 20:35:19 +00003103/* Note: takes ownership on name ptr */
3104static struct function *new_function(char *name)
3105{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003106 struct function **funcpp = find_function_slot(name);
3107 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003108
Denys Vlasenko873273d2009-09-12 14:47:41 +02003109 if (funcp != NULL) {
3110 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003111 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3112 if (!cmd) {
3113 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3114 free(funcp->name);
3115 /* Note: if !funcp->body, do not free body_as_string!
3116 * This is a special case of "-F name body" function:
3117 * body_as_string was not malloced! */
3118 if (funcp->body) {
3119 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003120# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003121 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003122# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003123 }
3124 } else {
3125 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3126 cmd->argv[0] = funcp->name;
3127 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003128# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003129 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003130# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003131 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003132 } else {
3133 debug_printf_exec("remembering new function '%s'\n", name);
3134 funcp = *funcpp = xzalloc(sizeof(*funcp));
3135 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003136 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003137
Denis Vlasenkobc569742009-04-12 20:35:19 +00003138 funcp->name = name;
3139 return funcp;
3140}
3141
Denis Vlasenko40e84372009-04-18 11:23:38 +00003142static void unset_func(const char *name)
3143{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003144 struct function **funcpp = find_function_slot(name);
3145 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003146
Denys Vlasenko873273d2009-09-12 14:47:41 +02003147 if (funcp != NULL) {
3148 debug_printf_exec("freeing function '%s'\n", funcp->name);
3149 *funcpp = funcp->next;
3150 /* funcp is unlinked now, deleting it.
3151 * Note: if !funcp->body, the function was created by
3152 * "-F name body", do not free ->body_as_string
3153 * and ->name as they were not malloced. */
3154 if (funcp->body) {
3155 free_pipe_list(funcp->body);
3156 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003157# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003158 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003159# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003160 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003161 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003162 }
3163}
3164
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003165# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003166#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003167 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003168# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003169static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003170 const struct function *funcp,
3171 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003172static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003173 const struct function *funcp,
3174 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003175{
3176# if BB_MMU
3177 int n = 1;
3178
3179 argv[0] = G.global_argv[0];
3180 G.global_argv = argv;
3181 while (*++argv)
3182 n++;
3183 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003184 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003185 n = run_list(funcp->body);
3186 fflush(NULL);
3187 _exit(n);
3188# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003189 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003190 funcp->body_as_string,
3191 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003192 argv + 1,
3193 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003194# endif
3195}
3196
3197static int run_function(const struct function *funcp, char **argv)
3198{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003199 int rc;
3200 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003201 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003202
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003203 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003204
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003205 /* "we are in function, ok to use return" */
3206 sv_flg = G.flag_return_in_progress;
3207 G.flag_return_in_progress = -1;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003208#if ENABLE_HUSH_LOCAL
3209 G.func_nest_level++;
3210#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003211
Denis Vlasenkobc569742009-04-12 20:35:19 +00003212 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003213# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003214 if (!funcp->body) {
3215 /* Function defined by -F */
3216 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003217 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003218 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003219# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003220 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003221 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003222 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003223
Denys Vlasenko295fef82009-06-03 12:47:26 +02003224#if ENABLE_HUSH_LOCAL
3225 {
3226 struct variable *var;
3227 struct variable **var_pp;
3228
3229 var_pp = &G.top_var;
3230 while ((var = *var_pp) != NULL) {
3231 if (var->func_nest_level < G.func_nest_level) {
3232 var_pp = &var->next;
3233 continue;
3234 }
3235 /* Unexport */
3236 if (var->flg_export)
3237 bb_unsetenv(var->varstr);
3238 /* Remove from global list */
3239 *var_pp = var->next;
3240 /* Free */
3241 if (!var->max_len)
3242 free(var->varstr);
3243 free(var);
3244 }
3245 G.func_nest_level--;
3246 }
3247#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003248 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003249
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003250 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003251
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003252 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003253}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003254#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003255
3256
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003257# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003258#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003259 exec_builtin(x, argv)
3260# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003261#define exec_builtin(to_free, x, argv) \
3262 exec_builtin(to_free, argv)
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003263# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003264static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003265 const struct built_in_command *x,
3266 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003267static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003268 const struct built_in_command *x,
3269 char **argv)
3270{
3271# if BB_MMU
3272 int rcode = x->function(argv);
3273 fflush(NULL);
3274 _exit(rcode);
3275# else
3276 /* On NOMMU, we must never block!
3277 * Example: { sleep 99 | read line; } & echo Ok
3278 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003279 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003280 argv[0],
3281 G.global_argv[0],
3282 G.global_argv + 1,
3283 argv);
3284# endif
3285}
3286
3287
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003288#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003289#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3290 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3291#define pseudo_exec(nommu_save, command, argv_expanded) \
3292 pseudo_exec(command, argv_expanded)
3293#endif
3294
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003295/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003296 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003297 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003298 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003299 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003300static void pseudo_exec_argv(nommu_save_t *nommu_save,
3301 char **argv, int assignment_cnt,
3302 char **argv_expanded) NORETURN;
3303static void pseudo_exec_argv(nommu_save_t *nommu_save,
3304 char **argv, int assignment_cnt,
3305 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003306{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003307 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003308
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003309 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003310 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003311 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003312
Denis Vlasenko9504e442008-10-29 01:19:15 +00003313 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003314#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003315 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003316 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003317 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003318 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003319#else
3320 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003321 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003322#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003323 if (argv_expanded) {
3324 argv = argv_expanded;
3325 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003326 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003327#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003328 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003329#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003330 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003331
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003332#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3333 if (strchr(argv[0], '/') != NULL)
3334 goto skip;
3335#endif
3336
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003337 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003338 * Depending on context, this might be redundant. But it's
3339 * easier to waste a few CPU cycles than it is to figure out
3340 * if this is one of those cases.
3341 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003342 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003343 /* On NOMMU, it is more expensive to re-execute shell
3344 * just in order to run echo or test builtin.
3345 * It's better to skip it here and run corresponding
3346 * non-builtin later. */
3347 const struct built_in_command *x;
3348 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003349 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003350 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003351 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003352 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003353#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003354 /* Check if the command matches any functions */
3355 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003356 const struct function *funcp = find_function(argv[0]);
3357 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003358 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003359 }
3360 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003361#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003362
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003363#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003364 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003365 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003366 int a = find_applet_by_name(argv[0]);
3367 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003368# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003369 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003370 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003371 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003372 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003373# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003374 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003375 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003376 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3377 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003378 /* If they called chroot or otherwise made the binary no longer
3379 * executable, fall through */
3380 }
3381 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003382#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003383
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003384#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003385 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003386#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003387 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003388 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003389 execvp(argv[0], argv);
Denis Vlasenkof9d4fc32009-04-21 20:40:51 +00003390 bb_perror_msg("can't execute '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00003391 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003392}
3393
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003394/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003395 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003396static void pseudo_exec(nommu_save_t *nommu_save,
3397 struct command *command,
3398 char **argv_expanded) NORETURN;
3399static void pseudo_exec(nommu_save_t *nommu_save,
3400 struct command *command,
3401 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003402{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003403 if (command->argv) {
3404 pseudo_exec_argv(nommu_save, command->argv,
3405 command->assignment_cnt, argv_expanded);
3406 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003407
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003408 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003409 /* Cases when we are here:
3410 * ( list )
3411 * { list } &
3412 * ... | ( list ) | ...
3413 * ... | { list } | ...
3414 */
3415#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003416 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003417 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003418 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003419 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003420 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003421 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003422 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003423#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003424 re_execute_shell(&nommu_save->argv_from_re_execing,
3425 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003426 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003427 G.global_argv + 1,
3428 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003429#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003430 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003431
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003432 /* Case when we are here: ... | >file */
3433 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003434 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003435}
3436
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003437#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003438static const char *get_cmdtext(struct pipe *pi)
3439{
3440 char **argv;
3441 char *p;
3442 int len;
3443
3444 /* This is subtle. ->cmdtext is created only on first backgrounding.
3445 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003446 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003447 if (pi->cmdtext)
3448 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003449 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003450 if (!argv || !argv[0]) {
3451 pi->cmdtext = xzalloc(1);
3452 return pi->cmdtext;
3453 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003454
3455 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003456 do {
3457 len += strlen(*argv) + 1;
3458 } while (*++argv);
3459 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003460 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003461 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003462 do {
3463 len = strlen(*argv);
3464 memcpy(p, *argv, len);
3465 p += len;
3466 *p++ = ' ';
3467 } while (*++argv);
3468 p[-1] = '\0';
3469 return pi->cmdtext;
3470}
3471
Eric Andersenbafd94f2001-05-02 16:11:59 +00003472static void insert_bg_job(struct pipe *pi)
3473{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003474 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003475 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003476
3477 /* Linear search for the ID of the job to use */
3478 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003479 for (job = G.job_list; job; job = job->next)
3480 if (job->jobid >= pi->jobid)
3481 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003482
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003483 /* Add job to the list of running jobs */
3484 jobp = &G.job_list;
3485 while ((job = *jobp) != NULL)
3486 jobp = &job->next;
3487 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003488
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003489 *job = *pi; /* physical copy */
3490 job->next = NULL;
3491 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3492 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003493 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003494 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003495 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003496 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003497 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003498
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003499 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003500 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3501 /* Last command's pid goes to $! */
3502 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3503 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003504}
3505
Eric Andersenbafd94f2001-05-02 16:11:59 +00003506static void remove_bg_job(struct pipe *pi)
3507{
3508 struct pipe *prev_pipe;
3509
Denis Vlasenko87a86552008-07-29 19:43:10 +00003510 if (pi == G.job_list) {
3511 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003512 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003513 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003514 while (prev_pipe->next != pi)
3515 prev_pipe = prev_pipe->next;
3516 prev_pipe->next = pi->next;
3517 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003518 if (G.job_list)
3519 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003520 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003521 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003522}
Eric Andersen028b65b2001-06-28 01:10:11 +00003523
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003524/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003525static void delete_finished_bg_job(struct pipe *pi)
3526{
3527 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003528 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003529 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003530 free(pi);
3531}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003532#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003533
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003534/* Check to see if any processes have exited -- if they
3535 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003536static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003537{
Eric Andersenc798b072001-06-22 06:23:03 +00003538 int attributes;
3539 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003540#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003541 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003542#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003543 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003544 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003545
Denis Vlasenkod5762932009-03-31 11:22:57 +00003546 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3547
Eric Andersenc798b072001-06-22 06:23:03 +00003548 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003549 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003550 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003551
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003552 errno = 0;
3553#if ENABLE_HUSH_FAST
3554 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3555//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3556//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003557 /* There was neither fork nor SIGCHLD since last waitpid */
3558 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003559 if (!G.we_have_children) {
3560 errno = ECHILD;
3561 return -1;
3562 }
3563 if (fg_pipe == NULL) { /* is WNOHANG set? */
3564 /* We have children, but they did not exit
3565 * or stop yet (we saw no SIGCHLD) */
3566 return 0;
3567 }
3568 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3569 }
3570#endif
3571
Denis Vlasenko1359da62007-04-21 23:27:30 +00003572/* Do we do this right?
3573 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003574 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003575 * [3]+ Stopped sleep 20 | false
3576 * bash-3.00# echo $?
3577 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003578 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003579 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003580 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003581 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003582 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003583 int dead;
3584
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003585#if ENABLE_HUSH_FAST
3586 i = G.count_SIGCHLD;
3587#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003588 childpid = waitpid(-1, &status, attributes);
3589 if (childpid <= 0) {
3590 if (childpid && errno != ECHILD)
3591 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003592#if ENABLE_HUSH_FAST
3593 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003594 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003595 G.handled_SIGCHLD = i;
3596//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3597 }
3598#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003599 break;
3600 }
3601 dead = WIFEXITED(status) || WIFSIGNALED(status);
3602
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003603#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003604 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003605 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003606 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3607 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003608 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003609 childpid, WTERMSIG(status), WEXITSTATUS(status));
3610 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003611 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003612 childpid, WEXITSTATUS(status));
3613#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003614 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003615 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003616 for (i = 0; i < fg_pipe->num_cmds; i++) {
3617 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3618 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003619 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003620 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003621 fg_pipe->cmds[i].pid = 0;
3622 fg_pipe->alive_cmds--;
3623 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003624 /* last process gives overall exitstatus */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003625 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003626 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003627 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003628 /* bash prints killing signal's name for *last*
3629 * process in pipe (prints just newline for SIGINT).
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003630 * Mimic this. Example: "sleep 5" + ^\
Denis Vlasenko40e84372009-04-18 11:23:38 +00003631 */
3632 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003633 int sig = WTERMSIG(status);
3634 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denis Vlasenko40e84372009-04-18 11:23:38 +00003635 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003636 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003637 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003638 fg_pipe->cmds[i].is_stopped = 1;
3639 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003640 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003641 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3642 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3643 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003644 /* All processes in fg pipe have exited or stopped */
3645/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3646 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3647 * and "killall -STOP cat" */
3648 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003649#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003650 if (fg_pipe->alive_cmds)
3651 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003652#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003653 return rcode;
3654 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02003655 if (!fg_pipe->alive_cmds)
3656 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003657 }
3658 /* There are still running processes in the fg pipe */
3659 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003660 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003661 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003662 }
3663
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003664#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003665 /* We asked to wait for bg or orphaned children */
3666 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003667 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003668 for (i = 0; i < pi->num_cmds; i++) {
3669 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003670 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003671 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003672 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003673 /* Happens when shell is used as init process (init=/bin/sh) */
3674 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003675 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003676
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003677 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003678 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003679 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003680 pi->cmds[i].pid = 0;
3681 pi->alive_cmds--;
3682 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003683 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003684 printf(JOB_STATUS_FORMAT, pi->jobid,
3685 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003686 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003687 }
3688 } else {
3689 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003690 pi->cmds[i].is_stopped = 1;
3691 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003692 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003693#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003694 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003695
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003696 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003697}
3698
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003699#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003700static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3701{
3702 pid_t p;
3703 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04003704 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003705 /* Job finished, move the shell to the foreground */
3706 p = getpgrp(); /* our process group id */
3707 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3708 tcsetpgrp(G_interactive_fd, p);
3709 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00003710 return rcode;
3711}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003712#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003713
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003714/* Start all the jobs, but don't wait for anything to finish.
3715 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003716 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003717 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003718 * to finish to determine the exit status of the pipe. If the pipe
3719 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003720 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003721 * return value.
3722 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003723 * Returns -1 only if started some children. IOW: we have to
3724 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003725 *
3726 * The only case when we do not need to [v]fork is when the pipe
3727 * is single, non-backgrounded, non-subshell command. Examples:
3728 * cmd ; ... { list } ; ...
3729 * cmd && ... { list } && ...
3730 * cmd || ... { list } || ...
3731 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3732 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003733 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00003734 *
3735 * Cases when we must fork:
3736 * non-single: cmd | cmd
3737 * backgrounded: cmd & { list } &
3738 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00003739 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003740static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003741{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003742 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003743 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003744 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003745 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003746 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003747 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003748 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003749 /* it is not always needed, but we aim to smaller code */
3750 int squirrel[] = { -1, -1, -1 };
3751 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003752
Denis Vlasenko552433b2009-04-04 19:29:21 +00003753 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003754 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003755
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003756 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003757 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003758 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003759 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003760
Denis Vlasenko552433b2009-04-04 19:29:21 +00003761 if (pi->num_cmds != 1
3762 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003763 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00003764 ) {
3765 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003766 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003767
Denis Vlasenko552433b2009-04-04 19:29:21 +00003768 pi->alive_cmds = 1;
3769
3770 debug_printf_exec(": group:%p argv:'%s'\n",
3771 command->group, command->argv ? command->argv[0] : "NONE");
3772
3773 if (command->group) {
3774#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003775 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003776 /* "executing" func () { list } */
3777 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003778
Denis Vlasenkobc569742009-04-12 20:35:19 +00003779 funcp = new_function(command->argv[0]);
3780 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003781 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003782# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003783 funcp->body_as_string = command->group_as_string;
3784 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003785# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003786 command->group = NULL;
3787 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00003788 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3789 funcp->parent_cmd = command;
3790 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003791
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003792 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3793 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00003794 return EXIT_SUCCESS;
3795 }
3796#endif
3797 /* { list } */
3798 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003799 rcode = 1; /* exitcode if redir failed */
3800 if (setup_redirects(command, squirrel) == 0) {
3801 debug_printf_exec(": run_list\n");
3802 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003803 }
Eric Andersen04407e52001-06-07 16:42:05 +00003804 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003805 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003806 debug_leave();
3807 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003808 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003809 }
3810
Denis Vlasenko552433b2009-04-04 19:29:21 +00003811 argv = command->argv ? command->argv : (char **) &null_ptr;
3812 {
3813 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003814#if ENABLE_HUSH_FUNCTIONS
3815 const struct function *funcp;
3816#else
3817 enum { funcp = 0 };
3818#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003819 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003820 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003821
Denis Vlasenko552433b2009-04-04 19:29:21 +00003822 if (argv[command->assignment_cnt] == NULL) {
3823 /* Assignments, but no command */
3824 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003825 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003826 restore_redirects(squirrel);
3827 /* Set shell variables */
3828 while (*argv) {
3829 p = expand_string_to_string(*argv);
3830 debug_printf_exec("set shell var:'%s'->'%s'\n",
3831 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003832 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003833 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00003834 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00003835 /* Do we need to flag set_local_var() errors?
3836 * "assignment to readonly var" and "putenv error"
3837 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003838 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003839 debug_leave();
3840 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003841 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00003842 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003843
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003844 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003845 if (0) {}
3846#if ENABLE_HUSH_BASH_COMPAT
3847 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003848 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3849 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003850#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003851#ifdef CMD_SINGLEWORD_NOGLOB_COND
3852 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3853 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3854
3855 }
3856#endif
3857 else {
3858 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3859 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003860
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003861 x = find_builtin(argv_expanded[0]);
3862#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003863 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003864 if (!x)
3865 funcp = find_function(argv_expanded[0]);
3866#endif
3867 if (x || funcp) {
3868 if (!funcp) {
3869 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3870 debug_printf("exec with redirects only\n");
3871 rcode = setup_redirects(command, NULL);
3872 goto clean_up_and_ret1;
3873 }
Eric Andersen25f27032001-04-26 23:22:31 +00003874 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003875 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003876 * This is perfect for work that comes after exec().
3877 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003878 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003879 rcode = setup_redirects(command, squirrel);
3880 if (rcode == 0) {
3881 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003882 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003883 if (!funcp) {
3884 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003885 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003886 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003887 fflush(NULL);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003888 }
3889#if ENABLE_HUSH_FUNCTIONS
3890 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02003891# if ENABLE_HUSH_LOCAL
3892 struct variable **sv;
3893 sv = G.shadowed_vars_pp;
3894 G.shadowed_vars_pp = &old_vars;
3895# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003896 debug_printf_exec(": function '%s' '%s'...\n",
3897 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003898 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003899# if ENABLE_HUSH_LOCAL
3900 G.shadowed_vars_pp = sv;
3901# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003902 }
3903#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003904 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003905#if ENABLE_FEATURE_SH_STANDALONE
3906 clean_up_and_ret:
3907#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003908 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003909 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003910 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003911 clean_up_and_ret1:
3912 free(argv_expanded);
3913 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003914 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003915 debug_printf_exec("run_pipe return %d\n", rcode);
3916 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003917 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003918
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003919#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003920 i = find_applet_by_name(argv_expanded[0]);
3921 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003922 rcode = setup_redirects(command, squirrel);
3923 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003924 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003925 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003926 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003927 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003928 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003929 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003930 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003931 }
3932#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00003933 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00003934 }
3935
Denis Vlasenko552433b2009-04-04 19:29:21 +00003936 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003937 /* NB: argv_expanded may already be created, and that
3938 * might include `cmd` runs! Do not rerun it! We *must*
3939 * use argv_expanded if it's non-NULL */
3940
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003941 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003942 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003943 nextin = 0;
3944
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003945 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003946 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003947#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003948 volatile nommu_save_t nommu_save;
3949 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003950 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003951 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003952 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003953#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003954 command = &(pi->cmds[i]);
3955 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003956 debug_printf_exec(": pipe member '%s' '%s'...\n",
3957 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003958 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003959 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00003960 }
Eric Andersen25f27032001-04-26 23:22:31 +00003961
3962 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003963 pipefds.rd = 0;
3964 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003965 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003966 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00003967
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003968 command->pid = BB_MMU ? fork() : vfork();
3969 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003970#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003971 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkod5762932009-03-31 11:22:57 +00003972
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003973 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00003974 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003975 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00003976 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003977 pgrp = pi->pgrp;
3978 if (pgrp < 0) /* true for 1st process only */
3979 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003980 if (setpgid(0, pgrp) == 0
3981 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04003982 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003983 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003984 /* We do it in *every* child, not just first,
3985 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003986 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003987 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003988 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003989#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003990 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3991 /* 1st cmd in backgrounded pipe
3992 * should have its stdin /dev/null'ed */
3993 close(0);
3994 if (open(bb_dev_null, O_RDONLY))
3995 xopen("/", O_RDONLY);
3996 } else {
3997 xmove_fd(nextin, 0);
3998 }
3999 xmove_fd(pipefds.wr, 1);
4000 if (pipefds.rd > 1)
4001 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004002 /* Like bash, explicit redirects override pipes,
4003 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004004 if (setup_redirects(command, NULL))
4005 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004006
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004007 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004008 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4009
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004010 /* Stores to nommu_save list of env vars putenv'ed
4011 * (NOMMU, on MMU we don't need that) */
4012 /* cast away volatility... */
4013 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004014 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004015 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004016
Denis Vlasenkof9375282009-04-05 19:13:39 +00004017 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004018#if ENABLE_HUSH_FAST
4019 G.count_SIGCHLD++;
4020//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4021#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004022 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004023#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004024 /* Clean up after vforked child */
4025 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004026 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004027 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004028 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004029#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004030 free(argv_expanded);
4031 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004032 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004033 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00004034 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004035 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004036 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004037#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004038 /* Second and next children need to know pid of first one */
4039 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004040 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004041#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004042 }
Eric Andersen25f27032001-04-26 23:22:31 +00004043
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004044 if (i)
4045 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004046 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004047 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004048 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004049 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004050 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004051
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004052 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004053 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004054 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4055 return 1;
4056 }
4057
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004058 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004059 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004060 return -1;
4061}
4062
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004063#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004064static void debug_print_tree(struct pipe *pi, int lvl)
4065{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004066 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004067 [PIPE_SEQ] = "SEQ",
4068 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004069 [PIPE_OR ] = "OR" ,
4070 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004071 };
4072 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004073 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00004074#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004075 [RES_IF ] = "IF" ,
4076 [RES_THEN ] = "THEN" ,
4077 [RES_ELIF ] = "ELIF" ,
4078 [RES_ELSE ] = "ELSE" ,
4079 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00004080#endif
4081#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004082 [RES_FOR ] = "FOR" ,
4083 [RES_WHILE] = "WHILE",
4084 [RES_UNTIL] = "UNTIL",
4085 [RES_DO ] = "DO" ,
4086 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004087#endif
4088#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004089 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00004090#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004091#if ENABLE_HUSH_CASE
4092 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004093 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004094 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004095 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004096 [RES_ESAC ] = "ESAC" ,
4097#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004098 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004099 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004100 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004101 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004102 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004103 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004104 "[noglob]",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004105#if ENABLE_HUSH_FUNCTIONS
4106 "func()",
4107#endif
4108 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004109
4110 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004111
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004112 pin = 0;
4113 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004114 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4115 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004116 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004117 while (prn < pi->num_cmds) {
4118 struct command *command = &pi->cmds[prn];
4119 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004120
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004121 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004122 lvl*2, "", prn,
4123 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004124 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004125 fprintf(stderr, " group %s: (argv=%p)\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004126 CMDTYPE[command->cmd_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004127 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004128 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004129 prn++;
4130 continue;
4131 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004132 if (argv) while (*argv) {
4133 fprintf(stderr, " '%s'", *argv);
4134 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004135 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004136 fprintf(stderr, "\n");
4137 prn++;
4138 }
4139 pi = pi->next;
4140 pin++;
4141 }
4142}
4143#endif
4144
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004145/* NB: called by pseudo_exec, and therefore must not modify any
4146 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004147static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004148{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004149#if ENABLE_HUSH_CASE
4150 char *case_word = NULL;
4151#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004152#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004153 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004154 char **for_lcur = NULL;
4155 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004156#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004157 smallint last_followup;
4158 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004159#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004160 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004161#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004162 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004163#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004164#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004165 smallint rword; /* enum reserved_style */
4166 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004167#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004168
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004169 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004170 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004171
Denis Vlasenko06810332007-05-21 23:30:54 +00004172#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004173 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004174 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4175 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004176 continue;
4177 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004178 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004179 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004180 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004181 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004182 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004183 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004184 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004185 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004186 continue;
4187 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004188 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4189 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004190 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004191 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004192 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004193 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004194 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004195 }
4196 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004197#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004198
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004199 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004200 * in order to return, no direct "return" statements please.
4201 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004202
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004203#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004204 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004205#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004206
Denis Vlasenko0e151382009-04-06 18:40:31 +00004207#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004208 rword = RES_NONE;
4209 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004210#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004211 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004212 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004213
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004214 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004215 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004216 if (G.flag_SIGINT)
4217 break;
4218
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004219 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004220 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4221 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004222#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004223 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004224 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004225 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004226 /* start of a loop: remember where loop starts */
4227 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004228 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004229 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004230#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004231 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004232 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004233 if ((rcode == 0 && last_followup == PIPE_OR)
4234 || (rcode != 0 && last_followup == PIPE_AND)
4235 ) {
4236 /* It is "<true> || CMD" or "<false> && CMD"
4237 * and we should not execute CMD */
4238 debug_printf_exec("skipped cmd because of || or &&\n");
4239 last_followup = pi->followup;
4240 continue;
4241 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004242 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004243 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004244 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004245#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004246 if (cond_code) {
4247 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004248 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004249 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004250 /* "if <false> THEN cmd": skip cmd */
4251 continue;
4252 }
4253 } else {
4254 if (rword == RES_ELSE || rword == RES_ELIF) {
4255 /* "if <true> then ... ELSE/ELIF cmd":
4256 * skip cmd and all following ones */
4257 break;
4258 }
4259 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004260#endif
4261#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004262 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004263 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004264 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004265
4266 static const char encoded_dollar_at[] ALIGN1 = {
4267 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4268 }; /* encoded representation of "$@" */
4269 static const char *const encoded_dollar_at_argv[] = {
4270 encoded_dollar_at, NULL
4271 }; /* argv list with one element: "$@" */
4272 char **vals;
4273
4274 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004275 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004276 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004277 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004278 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004279 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004280 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004281 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004282 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004283 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004284 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004285 debug_print_strings("for_list made from", vals);
4286 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004287 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004288 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004289 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004290 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004291 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004292 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004293 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004294 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004295 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004296 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004297 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004298 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004299 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 +02004300 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004301 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004302 if (rword == RES_IN) {
4303 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4304 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004305 if (rword == RES_DONE) {
4306 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004307 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004308#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004309#if ENABLE_HUSH_CASE
4310 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004311 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004312 continue;
4313 }
4314 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004315 char **argv;
4316
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004317 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4318 break;
4319 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004320 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004321 while (*argv) {
4322 char *pattern = expand_string_to_string(*argv);
4323 /* TODO: which FNM_xxx flags to use? */
4324 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4325 free(pattern);
4326 if (cond_code == 0) { /* match! we will execute this branch */
4327 free(case_word); /* make future "word)" stop */
4328 case_word = NULL;
4329 break;
4330 }
4331 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004332 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004333 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004334 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004335 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004336 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004337 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004338 }
4339#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004340 /* Just pressing <enter> in shell should check for jobs.
4341 * OTOH, in non-interactive shell this is useless
4342 * and only leads to extra job checks */
4343 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004344 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004345 goto check_jobs_and_continue;
4346 continue;
4347 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004348
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004349 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004350 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004351 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004352 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004353 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004354 {
4355 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004356#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004357 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004358#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004359 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4360 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004361 /* We ran a builtin, function, or group.
4362 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004363 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004364 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004365 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004366 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004367#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004368 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004369 if (G.flag_break_continue) {
4370 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004371 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004372 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004373 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004374 G.depth_break_continue--;
4375 if (G.depth_break_continue == 0)
4376 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004377 /* else: e.g. "continue 2" should *break* once, *then* continue */
4378 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004379 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004380 goto check_jobs_and_break;
4381 /* "continue": simulate end of loop */
4382 rword = RES_DONE;
4383 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004384 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004385#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004386#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004387 if (G.flag_return_in_progress == 1) {
4388 /* same as "goto check_jobs_and_break" */
4389 checkjobs(NULL);
4390 break;
4391 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004392#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004393 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004394 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004395 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004396 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4397 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004398 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004399#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004400 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004401 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004402#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004403 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004404 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004405 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004406#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004407 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004408 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004409 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004410 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004411 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004412 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004413#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004414 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004415 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004416 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004417 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004418 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004419 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004420 }
4421 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004422
4423 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004424#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004425 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004426 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004427#endif
4428#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004429 /* Beware of "while false; true; do ..."! */
4430 if (pi->next && pi->next->res_word == RES_DO) {
4431 if (rword == RES_WHILE) {
4432 if (rcode) {
4433 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004434 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004435 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4436 goto check_jobs_and_break;
4437 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004438 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004439 if (rword == RES_UNTIL) {
4440 if (!rcode) {
4441 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004442 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004443 checkjobs(NULL);
4444 break;
4445 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004446 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004447 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004448#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004449
4450 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004451 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004452 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004453
4454#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004455 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004456#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004457#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004458 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004459 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004460 free(for_list);
4461#endif
4462#if ENABLE_HUSH_CASE
4463 free(case_word);
4464#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004465 debug_leave();
4466 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004467 return rcode;
4468}
4469
Eric Andersen25f27032001-04-26 23:22:31 +00004470/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004471static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004472{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004473 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004474 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004475 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004476 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004477 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004478 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004479 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004480 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004481 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004482 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004483 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004484 return rcode;
4485}
4486
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004487
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004488static struct pipe *new_pipe(void)
4489{
Eric Andersen25f27032001-04-26 23:22:31 +00004490 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004491 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004492 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004493 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004494 return pi;
4495}
4496
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004497/* Command (member of a pipe) is complete, or we start a new pipe
4498 * if ctx->command is NULL.
4499 * No errors possible here.
4500 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004501static int done_command(struct parse_context *ctx)
4502{
4503 /* The command is really already in the pipe structure, so
4504 * advance the pipe counter and make a new, null command. */
4505 struct pipe *pi = ctx->pipe;
4506 struct command *command = ctx->command;
4507
4508 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004509 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004510 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004511 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004512 }
4513 pi->num_cmds++;
4514 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004515 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004516 } else {
4517 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4518 }
4519
4520 /* Only real trickiness here is that the uncommitted
4521 * command structure is not counted in pi->num_cmds. */
4522 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004523 ctx->command = command = &pi->cmds[pi->num_cmds];
4524 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004525 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004526 return pi->num_cmds; /* used only for 0/nonzero check */
4527}
4528
4529static void done_pipe(struct parse_context *ctx, pipe_style type)
4530{
4531 int not_null;
4532
4533 debug_printf_parse("done_pipe entered, followup %d\n", type);
4534 /* Close previous command */
4535 not_null = done_command(ctx);
4536 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004537#if HAS_KEYWORDS
4538 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4539 ctx->ctx_inverted = 0;
4540 ctx->pipe->res_word = ctx->ctx_res_w;
4541#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004542
4543 /* Without this check, even just <enter> on command line generates
4544 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004545 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004546 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004547#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004548 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004549#endif
4550#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004551 || ctx->ctx_res_w == RES_DONE
4552 || ctx->ctx_res_w == RES_FOR
4553 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004554#endif
4555#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004556 || ctx->ctx_res_w == RES_ESAC
4557#endif
4558 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004559 struct pipe *new_p;
4560 debug_printf_parse("done_pipe: adding new pipe: "
4561 "not_null:%d ctx->ctx_res_w:%d\n",
4562 not_null, ctx->ctx_res_w);
4563 new_p = new_pipe();
4564 ctx->pipe->next = new_p;
4565 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004566 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004567 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004568 * This is used to control execution.
4569 * RES_FOR and RES_IN are NOT sticky (needed to support
4570 * cases where variable or value happens to match a keyword):
4571 */
4572#if ENABLE_HUSH_LOOPS
4573 if (ctx->ctx_res_w == RES_FOR
4574 || ctx->ctx_res_w == RES_IN)
4575 ctx->ctx_res_w = RES_NONE;
4576#endif
4577#if ENABLE_HUSH_CASE
4578 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004579 ctx->ctx_res_w = RES_CASE_BODY;
4580 if (ctx->ctx_res_w == RES_CASE)
4581 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004582#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004583 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004584 /* Create the memory for command, roughly:
4585 * ctx->pipe->cmds = new struct command;
4586 * ctx->command = &ctx->pipe->cmds[0];
4587 */
4588 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004589 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004590 }
4591 debug_printf_parse("done_pipe return\n");
4592}
4593
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004594static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004595{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004596 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004597 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004598 /* Create the memory for command, roughly:
4599 * ctx->pipe->cmds = new struct command;
4600 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004601 */
4602 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004603}
4604
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004605/* If a reserved word is found and processed, parse context is modified
4606 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004607 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004608#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004609struct reserved_combo {
4610 char literal[6];
4611 unsigned char res;
4612 unsigned char assignment_flag;
4613 int flag;
4614};
4615enum {
4616 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004617#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004618 FLAG_IF = (1 << RES_IF ),
4619 FLAG_THEN = (1 << RES_THEN ),
4620 FLAG_ELIF = (1 << RES_ELIF ),
4621 FLAG_ELSE = (1 << RES_ELSE ),
4622 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004623#endif
4624#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004625 FLAG_FOR = (1 << RES_FOR ),
4626 FLAG_WHILE = (1 << RES_WHILE),
4627 FLAG_UNTIL = (1 << RES_UNTIL),
4628 FLAG_DO = (1 << RES_DO ),
4629 FLAG_DONE = (1 << RES_DONE ),
4630 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004631#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004632#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004633 FLAG_MATCH = (1 << RES_MATCH),
4634 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004635#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004636 FLAG_START = (1 << RES_XXXX ),
4637};
4638
4639static const struct reserved_combo* match_reserved_word(o_string *word)
4640{
Eric Andersen25f27032001-04-26 23:22:31 +00004641 /* Mostly a list of accepted follow-up reserved words.
4642 * FLAG_END means we are done with the sequence, and are ready
4643 * to turn the compound list into a command.
4644 * FLAG_START means the word must start a new compound list.
4645 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004646 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00004647#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004648 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4649 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4650 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4651 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4652 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4653 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004654#endif
4655#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004656 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4657 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4658 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4659 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4660 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4661 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004662#endif
4663#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004664 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4665 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004666#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004667 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004668 const struct reserved_combo *r;
4669
4670 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4671 if (strcmp(word->data, r->literal) == 0)
4672 return r;
4673 }
4674 return NULL;
4675}
Denis Vlasenkobb929512009-04-16 10:59:40 +00004676/* Return 0: not a keyword, 1: keyword
4677 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004678static int reserved_word(o_string *word, struct parse_context *ctx)
4679{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004680#if ENABLE_HUSH_CASE
4681 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004682 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004683 };
4684#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004685 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004686
Denis Vlasenkobb929512009-04-16 10:59:40 +00004687 if (word->o_quoted)
4688 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004689 r = match_reserved_word(word);
4690 if (!r)
4691 return 0;
4692
4693 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004694#if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004695 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4696 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004697 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004698 } else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004699#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004700 if (r->flag == 0) { /* '!' */
4701 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004702 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004703 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004704 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004705 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004706 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004707 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004708 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004709 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004710
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004711 old = xmalloc(sizeof(*old));
4712 debug_printf_parse("push stack %p\n", old);
4713 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004714 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004715 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004716 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004717 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004718 ctx->ctx_res_w = RES_SNTX;
4719 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004720 } else {
4721 /* "{...} fi" is ok. "{...} if" is not
4722 * Example:
4723 * if { echo foo; } then { echo bar; } fi */
4724 if (ctx->command->group)
4725 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004726 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004727
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004728 ctx->ctx_res_w = r->res;
4729 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004730 word->o_assignment = r->assignment_flag;
4731
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004732 if (ctx->old_flag & FLAG_END) {
4733 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004734
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004735 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004736 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004737 old = ctx->stack;
4738 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004739 old->command->cmd_type = CMD_NORMAL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004740#if !BB_MMU
4741 o_addstr(&old->as_string, ctx->as_string.data);
4742 o_free_unsafe(&ctx->as_string);
4743 old->command->group_as_string = xstrdup(old->as_string.data);
4744 debug_printf_parse("pop, remembering as:'%s'\n",
4745 old->command->group_as_string);
4746#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004747 *ctx = *old; /* physical copy */
4748 free(old);
4749 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004750 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004751}
Denis Vlasenko06810332007-05-21 23:30:54 +00004752#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004753
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004754/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004755 * Normal return is 0. Syntax errors return 1.
4756 * Note: on return, word is reset, but not o_free'd!
4757 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004758static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004759{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004760 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004761
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004762 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004763 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004764 debug_printf_parse("done_word return 0: true null, ignored\n");
4765 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004766 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004767
Eric Andersen25f27032001-04-26 23:22:31 +00004768 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004769 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4770 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004771 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4772 * "2.7 Redirection
4773 * ...the word that follows the redirection operator
4774 * shall be subjected to tilde expansion, parameter expansion,
4775 * command substitution, arithmetic expansion, and quote
4776 * removal. Pathname expansion shall not be performed
4777 * on the word by a non-interactive shell; an interactive
4778 * shell may perform it, but shall do so only when
4779 * the expansion would result in one word."
4780 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004781 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004782 /* Cater for >\file case:
4783 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4784 * Same with heredocs:
4785 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4786 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004787 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4788 unbackslash(ctx->pending_redirect->rd_filename);
4789 /* Is it <<"HEREDOC"? */
4790 if (word->o_quoted) {
4791 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4792 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004793 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004794 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004795 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004796 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004797 /* If this word wasn't an assignment, next ones definitely
4798 * can't be assignments. Even if they look like ones. */
4799 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4800 && word->o_assignment != WORD_IS_KEYWORD
4801 ) {
4802 word->o_assignment = NOT_ASSIGNMENT;
4803 } else {
4804 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4805 command->assignment_cnt++;
4806 word->o_assignment = MAYBE_ASSIGNMENT;
4807 }
4808
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004809#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004810# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004811 if (ctx->ctx_dsemicolon
4812 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4813 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004814 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004815 /* ctx->ctx_res_w = RES_MATCH; */
4816 ctx->ctx_dsemicolon = 0;
4817 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004818# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004819 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004820# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004821 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4822 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004823# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004824# if ENABLE_HUSH_CASE
4825 && ctx->ctx_res_w != RES_CASE
4826# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004827 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004828 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004829 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004830 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004831 debug_printf_parse("done_word return %d\n",
4832 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004833 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004834 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004835# ifdef CMD_SINGLEWORD_NOGLOB_COND
4836 if (strcmp(word->data, "export") == 0
4837# if ENABLE_HUSH_LOCAL
4838 || strcmp(word->data, "local") == 0
4839# endif
4840 ) {
4841 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4842 } else
4843# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004844# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004845 if (strcmp(word->data, "[[") == 0) {
4846 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4847 }
4848 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004849# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004850 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004851#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00004852 if (command->group) {
4853 /* "{ echo foo; } echo bar" - bad */
4854 syntax_error_at(word->data);
4855 debug_printf_parse("done_word return 1: syntax error, "
4856 "groups and arglists don't mix\n");
4857 return 1;
4858 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004859 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004860 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4861 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004862 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004863 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004864 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004865 char *p = word->data;
4866 while (p[0] == SPECIAL_VAR_SYMBOL
4867 && (p[1] & 0x7f) == '@'
4868 && p[2] == SPECIAL_VAR_SYMBOL
4869 ) {
4870 p += 3;
4871 }
4872 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004873 /* saw no "$@", or not only "$@" but some
4874 * real text is there too */
4875 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004876 * e.g. "", $empty"" etc to not disappear */
4877 o_addchr(word, SPECIAL_VAR_SYMBOL);
4878 o_addchr(word, SPECIAL_VAR_SYMBOL);
4879 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004880 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004881 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004882 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004883 }
Eric Andersen25f27032001-04-26 23:22:31 +00004884
Denis Vlasenko06810332007-05-21 23:30:54 +00004885#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004886 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004887 if (word->o_quoted
4888 || !is_well_formed_var_name(command->argv[0], '\0')
4889 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004890 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004891 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004892 return 1;
4893 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004894 /* Force FOR to have just one word (variable name) */
4895 /* NB: basically, this makes hush see "for v in ..."
4896 * syntax as if it is "for v; in ...". FOR and IN become
4897 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004898 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004899 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004900#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004901#if ENABLE_HUSH_CASE
4902 /* Force CASE to have just one word */
4903 if (ctx->ctx_res_w == RES_CASE) {
4904 done_pipe(ctx, PIPE_SEQ);
4905 }
4906#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004907
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004908 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004909
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004910 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004911 return 0;
4912}
4913
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004914
4915/* Peek ahead in the input to find out if we have a "&n" construct,
4916 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004917 * Return:
4918 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4919 * REDIRFD_SYNTAX_ERR if syntax error,
4920 * REDIRFD_TO_FILE if no & was seen,
4921 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004922 */
4923#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004924#define parse_redir_right_fd(as_string, input) \
4925 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004926#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004927static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004928{
4929 int ch, d, ok;
4930
4931 ch = i_peek(input);
4932 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004933 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004934
4935 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004936 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004937 ch = i_peek(input);
4938 if (ch == '-') {
4939 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004940 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004941 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004942 }
4943 d = 0;
4944 ok = 0;
4945 while (ch != EOF && isdigit(ch)) {
4946 d = d*10 + (ch-'0');
4947 ok = 1;
4948 ch = i_getch(input);
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 }
4952 if (ok) return d;
4953
4954//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4955
4956 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004957 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004958}
4959
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004960/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004961 */
4962static int parse_redirect(struct parse_context *ctx,
4963 int fd,
4964 redir_type style,
4965 struct in_str *input)
4966{
4967 struct command *command = ctx->command;
4968 struct redir_struct *redir;
4969 struct redir_struct **redirp;
4970 int dup_num;
4971
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004972 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004973 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004974 /* Check for a '>&1' type redirect */
4975 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4976 if (dup_num == REDIRFD_SYNTAX_ERR)
4977 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004978 } else {
4979 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004980 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004981 if (dup_num) { /* <<-... */
4982 ch = i_getch(input);
4983 nommu_addchr(&ctx->as_string, ch);
4984 ch = i_peek(input);
4985 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004986 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004987
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004988 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004989 int ch = i_peek(input);
4990 if (ch == '|') {
4991 /* >|FILE redirect ("clobbering" >).
4992 * Since we do not support "set -o noclobber" yet,
4993 * >| and > are the same for now. Just eat |.
4994 */
4995 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004996 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004997 }
4998 }
4999
5000 /* Create a new redir_struct and append it to the linked list */
5001 redirp = &command->redirects;
5002 while ((redir = *redirp) != NULL) {
5003 redirp = &(redir->next);
5004 }
5005 *redirp = redir = xzalloc(sizeof(*redir));
5006 /* redir->next = NULL; */
5007 /* redir->rd_filename = NULL; */
5008 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005009 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005010
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005011 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5012 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005013
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005014 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005015 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005016 /* Erik had a check here that the file descriptor in question
5017 * is legit; I postpone that to "run time"
5018 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005019 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5020 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005021 } else {
5022 /* Set ctx->pending_redirect, so we know what to do at the
5023 * end of the next parsed word. */
5024 ctx->pending_redirect = redir;
5025 }
5026 return 0;
5027}
5028
Eric Andersen25f27032001-04-26 23:22:31 +00005029/* If a redirect is immediately preceded by a number, that number is
5030 * supposed to tell which file descriptor to redirect. This routine
5031 * looks for such preceding numbers. In an ideal world this routine
5032 * needs to handle all the following classes of redirects...
5033 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5034 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5035 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5036 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005037 *
5038 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5039 * "2.7 Redirection
5040 * ... If n is quoted, the number shall not be recognized as part of
5041 * the redirection expression. For example:
5042 * echo \2>a
5043 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005044 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005045 *
5046 * A -1 return means no valid number was found,
5047 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005048 */
5049static int redirect_opt_num(o_string *o)
5050{
5051 int num;
5052
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005053 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005054 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005055 num = bb_strtou(o->data, NULL, 10);
5056 if (errno || num < 0)
5057 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005058 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005059 return num;
5060}
5061
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005062#if BB_MMU
5063#define fetch_till_str(as_string, input, word, skip_tabs) \
5064 fetch_till_str(input, word, skip_tabs)
5065#endif
5066static char *fetch_till_str(o_string *as_string,
5067 struct in_str *input,
5068 const char *word,
5069 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005070{
5071 o_string heredoc = NULL_O_STRING;
5072 int past_EOL = 0;
5073 int ch;
5074
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005075 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005076 while (1) {
5077 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005078 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005079 if (ch == '\n') {
5080 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5081 heredoc.data[past_EOL] = '\0';
5082 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5083 return heredoc.data;
5084 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005085 do {
5086 o_addchr(&heredoc, ch);
5087 past_EOL = heredoc.length;
5088 jump_in:
5089 do {
5090 ch = i_getch(input);
5091 nommu_addchr(as_string, ch);
5092 } while (skip_tabs && ch == '\t');
5093 } while (ch == '\n');
5094 }
5095 if (ch == EOF) {
5096 o_free_unsafe(&heredoc);
5097 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005098 }
5099 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005100 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005101 }
5102}
5103
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005104/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5105 * and load them all. There should be exactly heredoc_cnt of them.
5106 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005107static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5108{
5109 struct pipe *pi = ctx->list_head;
5110
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005111 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005112 int i;
5113 struct command *cmd = pi->cmds;
5114
5115 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5116 pi->num_cmds,
5117 cmd->argv ? cmd->argv[0] : "NONE");
5118 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005119 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005120
5121 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5122 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005123 while (redir) {
5124 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005125 char *p;
5126
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005127 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005128 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005129 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005130 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005131 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005132 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005133 return 1;
5134 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005135 free(redir->rd_filename);
5136 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005137 heredoc_cnt--;
5138 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005139 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005140 }
5141 cmd++;
5142 }
5143 pi = pi->next;
5144 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005145#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005146 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005147 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005148 bb_error_msg_and_die("heredoc BUG 2");
5149#endif
5150 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005151}
5152
5153
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005154#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005155static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005156{
5157 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00005158 int pid, channel[2];
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005159#if !BB_MMU
5160 char **to_free;
5161#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005162
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005163 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00005164 pid = BB_MMU ? fork() : vfork();
5165 if (pid < 0)
5166 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005167
Denis Vlasenko05743d72008-02-10 12:10:08 +00005168 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005169 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005170 /* Process substitution is not considered to be usual
5171 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005172 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5173 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005174 bb_signals(0
5175 + (1 << SIGTSTP)
5176 + (1 << SIGTTIN)
5177 + (1 << SIGTTOU)
5178 , SIG_IGN);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005179 close(channel[0]); /* NB: close _first_, then move fd! */
5180 xmove_fd(channel[1], 1);
5181 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005182 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005183 /* Awful hack for `trap` or $(trap).
5184 *
5185 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5186 * contains an example where "trap" is executed in a subshell:
5187 *
5188 * save_traps=$(trap)
5189 * ...
5190 * eval "$save_traps"
5191 *
5192 * Standard does not say that "trap" in subshell shall print
5193 * parent shell's traps. It only says that its output
5194 * must have suitable form, but then, in the above example
5195 * (which is not supposed to be normative), it implies that.
5196 *
5197 * bash (and probably other shell) does implement it
5198 * (traps are reset to defaults, but "trap" still shows them),
5199 * but as a result, "trap" logic is hopelessly messed up:
5200 *
5201 * # trap
5202 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5203 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5204 * # true | trap <--- trap is in subshell - no output (ditto)
5205 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5206 * trap -- 'echo Ho' SIGWINCH
5207 * # echo `(trap)` <--- in subshell in subshell - output
5208 * trap -- 'echo Ho' SIGWINCH
5209 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5210 * trap -- 'echo Ho' SIGWINCH
5211 *
5212 * The rules when to forget and when to not forget traps
5213 * get really complex and nonsensical.
5214 *
5215 * Our solution: ONLY bare $(trap) or `trap` is special.
5216 */
5217 s = skip_whitespace(s);
5218 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5219 {
5220 static const char *const argv[] = { NULL, NULL };
5221 builtin_trap((char**)argv);
5222 exit(0); /* not _exit() - we need to fflush */
5223 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005224#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005225 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005226 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005227 _exit(G.last_exitcode);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005228#else
5229 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005230 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5231 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005232 * echo OK
5233 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005234 re_execute_shell(&to_free,
5235 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005236 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005237 G.global_argv + 1,
5238 NULL);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005239#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005240 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005241
5242 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005243#if ENABLE_HUSH_FAST
5244 G.count_SIGCHLD++;
5245//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);
5246#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005247 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005248#if !BB_MMU
5249 free(to_free);
5250#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005251 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00005252 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00005253 return pf;
5254}
5255
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005256/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005257static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005258{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005259 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00005260 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005261 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005262
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005263 pf = generate_stream_from_string(s);
5264 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00005265 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005266 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00005267
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005268 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005269 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005270 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005271 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005272 if (ch == '\n') {
5273 eol_cnt++;
5274 continue;
5275 }
5276 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005277 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005278 eol_cnt--;
5279 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005280 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005281 }
5282
5283 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005284 /* Note: we got EOF, and we just close the read end of the pipe.
5285 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005286 * Try these:
5287 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5288 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005289 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005290 fclose(pf);
5291 debug_printf("closed FILE from child. return 0\n");
5292 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005293}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005294#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005295
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005296static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005297 struct in_str *input, int ch)
5298{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005299 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005300 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005301 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005302 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005303 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005304 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005305
5306 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005307#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005308 if (ch == '(' && !dest->o_quoted) {
5309 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005310 if (done_word(dest, ctx))
5311 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005312 if (!command->argv)
5313 goto skip; /* (... */
5314 if (command->argv[1]) { /* word word ... (... */
5315 syntax_error_unexpected_ch('(');
5316 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005317 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005318 /* it is "word(..." or "word (..." */
5319 do
5320 ch = i_getch(input);
5321 while (ch == ' ' || ch == '\t');
5322 if (ch != ')') {
5323 syntax_error_unexpected_ch(ch);
5324 return 1;
5325 }
5326 nommu_addchr(&ctx->as_string, ch);
5327 do
5328 ch = i_getch(input);
5329 while (ch == ' ' || ch == '\t' || ch == '\n');
5330 if (ch != '{') {
5331 syntax_error_unexpected_ch(ch);
5332 return 1;
5333 }
5334 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005335 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005336 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005337 }
5338#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005339 if (command->argv /* word [word]{... */
5340 || dest->length /* word{... */
5341 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005342 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005343 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005344 debug_printf_parse("parse_group return 1: "
5345 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005346 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005347 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005348
5349#if ENABLE_HUSH_FUNCTIONS
5350 skip:
5351#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005352 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005353 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005354 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005355 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005356 } else {
5357 /* bash does not allow "{echo...", requires whitespace */
5358 ch = i_getch(input);
5359 if (ch != ' ' && ch != '\t' && ch != '\n') {
5360 syntax_error_unexpected_ch(ch);
5361 return 1;
5362 }
5363 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005364 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005365
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005366 {
5367#if !BB_MMU
5368 char *as_string = NULL;
5369#endif
5370 pipe_list = parse_stream(&as_string, input, endch);
5371#if !BB_MMU
5372 if (as_string)
5373 o_addstr(&ctx->as_string, as_string);
5374#endif
5375 /* empty ()/{} or parse error? */
5376 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005377 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005378#if !BB_MMU
5379 free(as_string);
5380#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005381 debug_printf_parse("parse_group return 1: "
5382 "parse_stream returned %p\n", pipe_list);
5383 return 1;
5384 }
5385 command->group = pipe_list;
5386#if !BB_MMU
5387 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5388 command->group_as_string = as_string;
5389 debug_printf_parse("end of group, remembering as:'%s'\n",
5390 command->group_as_string);
5391#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005392 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005393 debug_printf_parse("parse_group return 0\n");
5394 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005395 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005396}
5397
Mike Frysinger98c52642009-04-02 10:02:37 +00005398#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005399/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005400static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005401/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005402static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005403{
5404 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005405 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005406 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005407 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005408 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005409 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005410 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005411 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005412 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005413 }
5414}
5415/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005416static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005417{
5418 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005419 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005420 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005421 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005422 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005423 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005424 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005425 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005426 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005427 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005428 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005429 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005430 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005431 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005432 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005433 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005434 continue;
5435 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005436 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005437 }
5438}
5439/* Process `cmd` - copy contents until "`" is seen. Complicated by
5440 * \` quoting.
5441 * "Within the backquoted style of command substitution, backslash
5442 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5443 * The search for the matching backquote shall be satisfied by the first
5444 * backquote found without a preceding backslash; during this search,
5445 * if a non-escaped backquote is encountered within a shell comment,
5446 * a here-document, an embedded command substitution of the $(command)
5447 * form, or a quoted string, undefined results occur. A single-quoted
5448 * or double-quoted string that begins, but does not end, within the
5449 * "`...`" sequence produces undefined results."
5450 * Example Output
5451 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5452 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005453static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005454{
5455 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005456 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005457 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005458 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005459 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005460 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005461 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005462 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005463 if (ch == '\\') {
5464 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005465 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005466 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005467 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005468 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005469 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005470 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005471 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005472 ch = ch2;
5473 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005474 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005475 }
5476}
5477/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5478 * quoting and nested ()s.
5479 * "With the $(command) style of command substitution, all characters
5480 * following the open parenthesis to the matching closing parenthesis
5481 * constitute the command. Any valid shell script can be used for command,
5482 * except a script consisting solely of redirections which produces
5483 * unspecified results."
5484 * Example Output
5485 * echo $(echo '(TEST)' BEST) (TEST) BEST
5486 * echo $(echo 'TEST)' BEST) TEST) BEST
5487 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5488 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005489static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005490{
5491 int count = 0;
5492 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005493 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005494 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005495 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005496 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005497 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005498 if (ch == '(')
5499 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005500 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005501 if (--count < 0) {
5502 if (!dbl)
5503 break;
5504 if (i_peek(input) == ')') {
5505 i_getch(input);
5506 break;
5507 }
5508 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005509 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005510 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005511 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005512 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005513 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005514 continue;
5515 }
5516 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005517 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005518 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005519 continue;
5520 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005521 if (ch == '\\') {
5522 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005523 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005524 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005525 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005526 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005527 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005528 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005529 continue;
5530 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005531 }
5532}
Mike Frysinger98c52642009-04-02 10:02:37 +00005533#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005534
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005535/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005536#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005537#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005538 handle_dollar(dest, input)
5539#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005540static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005541 o_string *dest,
5542 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005543{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005544 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005545 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005546
5547 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005548 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005549 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005550 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005551 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005552 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005553 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005554 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005555 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005556 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005557 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005558 if (!isalnum(ch) && ch != '_')
5559 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005560 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005561 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005562 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005563 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005564 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005565 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005566 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005567 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005568 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005569 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005570 o_addchr(dest, ch | quote_mask);
5571 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005572 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005573 case '$': /* pid */
5574 case '!': /* last bg pid */
5575 case '?': /* last exit code */
5576 case '#': /* number of args */
5577 case '*': /* args */
5578 case '@': /* args */
5579 goto make_one_char_var;
5580 case '{': {
5581 bool first_char, all_digits;
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005582 int expansion;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005583
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005584 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005585 nommu_addchr(as_string, ch);
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005586 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5587
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00005588 /* TODO: maybe someone will try to escape the '}' */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005589 expansion = 0;
5590 first_char = true;
5591 all_digits = false;
5592 while (1) {
5593 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005594 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005595 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005596 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005597 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005598
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005599 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005600 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005601 /* ${#var}: length of var contents */
5602 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005603 }
5604 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005605 all_digits = true;
5606 goto char_ok;
5607 }
Mike Frysingerdc3bc402009-06-01 14:09:09 -04005608 /* They're being verbose and doing ${?} */
5609 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5610 goto char_ok;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005611 }
5612
5613 if (expansion < 2
5614 && ( (all_digits && !isdigit(ch))
5615 || (!all_digits && !isalnum(ch) && ch != '_')
5616 )
5617 ) {
5618 /* handle parameter expansions
5619 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5620 */
5621 if (first_char)
5622 goto case_default;
5623 switch (ch) {
5624 case ':': /* null modifier */
5625 if (expansion == 0) {
5626 debug_printf_parse(": null modifier\n");
5627 ++expansion;
5628 break;
5629 }
5630 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005631 case '#': /* remove prefix */
5632 case '%': /* remove suffix */
5633 if (expansion == 0) {
5634 debug_printf_parse(": remove suffix/prefix\n");
5635 expansion = 2;
5636 break;
5637 }
5638 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005639 case '-': /* default value */
5640 case '=': /* assign default */
5641 case '+': /* alternative */
5642 case '?': /* error indicate */
5643 debug_printf_parse(": parameter expansion\n");
5644 expansion = 2;
5645 break;
5646 default:
5647 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005648 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005649 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5650 return 1;
5651 }
5652 }
5653 char_ok:
5654 debug_printf_parse(": '%c'\n", ch);
5655 o_addchr(dest, ch | quote_mask);
5656 quote_mask = 0;
5657 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005658 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005659 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5660 break;
5661 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005662#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005663 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005664# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005665 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005666# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005667 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005668 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005669# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005670 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005671 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005672 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005673 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5674 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005675# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005676 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005677# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005678 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005679# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005680 if (as_string) {
5681 o_addstr(as_string, dest->data + pos);
5682 o_addchr(as_string, ')');
5683 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005684 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005685# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005686 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005687 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005688 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005689# endif
5690# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005691 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5692 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005693# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005694 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005695# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005696 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005697# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005698 if (as_string) {
5699 o_addstr(as_string, dest->data + pos);
5700 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005701 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005702# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005703 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005704# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005705 break;
5706 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005707#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005708 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005709 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005710 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005711 ch = i_peek(input);
5712 if (isalnum(ch)) { /* it's $_name or $_123 */
5713 ch = '_';
5714 goto make_var;
5715 }
5716 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005717 /* TODO: $_ and $-: */
5718 /* $_ Shell or shell script name; or last argument of last command
5719 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5720 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005721 /* $- Option flags set by set builtin or shell options (-i etc) */
5722 default:
5723 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005724 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005725 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005726 return 0;
5727}
5728
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005729#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005730#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005731 parse_stream_dquoted(dest, input, dquote_end)
5732#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005733static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005734 o_string *dest,
5735 struct in_str *input,
5736 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005737{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005738 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005739 int next;
5740
5741 again:
5742 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005743 if (ch != EOF)
5744 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005745 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005746 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005747 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005748 debug_printf_parse("parse_stream_dquoted return 0\n");
5749 return 0;
5750 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005751 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005752 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005753 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005754 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005755 }
5756 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005757 if (ch != '\n') {
5758 next = i_peek(input);
5759 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005760 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5761 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005762 if (ch == '\\') {
5763 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005764 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005765 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005766 }
5767 /* bash:
5768 * "The backslash retains its special meaning [in "..."]
5769 * only when followed by one of the following characters:
5770 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005771 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005772 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005773 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00005774 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005775 if (ch != '\n') {
5776 o_addqchr(dest, ch);
5777 nommu_addchr(as_string, ch);
5778 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005779 } else {
5780 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00005781 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005782 }
5783 goto again;
5784 }
5785 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005786 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005787 debug_printf_parse("parse_stream_dquoted return 1: "
5788 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005789 return 1;
5790 }
5791 goto again;
5792 }
5793#if ENABLE_HUSH_TICK
5794 if (ch == '`') {
5795 //int pos = dest->length;
5796 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5797 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005798 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005799 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5800 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005801 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005802 }
5803#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005804 o_addQchr(dest, ch);
5805 if (ch == '='
5806 && (dest->o_assignment == MAYBE_ASSIGNMENT
5807 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005808 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00005809 ) {
5810 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5811 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005812 goto again;
5813}
5814
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005815/*
5816 * Scan input until EOF or end_trigger char.
5817 * Return a list of pipes to execute, or NULL on EOF
5818 * or if end_trigger character is met.
5819 * On syntax error, exit is shell is not interactive,
5820 * reset parsing machinery and start parsing anew,
5821 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005822 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005823static struct pipe *parse_stream(char **pstring,
5824 struct in_str *input,
5825 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005826{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005827 struct parse_context ctx;
5828 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005829 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005830 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005831
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005832 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00005833 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005834 * found. When recursing, quote state is passed in via dest->o_escape.
5835 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005836 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005837 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005838 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005839
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005840 G.ifs = get_local_var_value("IFS");
5841 if (G.ifs == NULL)
5842 G.ifs = " \t\n";
5843
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005844 reset:
5845#if ENABLE_HUSH_INTERACTIVE
5846 input->promptmode = 0; /* PS1 */
5847#endif
5848 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5849 initialize_context(&ctx);
5850 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005851 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005852 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005853 const char *is_ifs;
5854 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005855 int ch;
5856 int next;
5857 int redir_fd;
5858 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005859
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005860 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005861 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005862 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005863 goto parse_error;
5864 }
5865 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005866 is_in_dquote = 0;
5867 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005868 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005869 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5870 ch, ch, dest.o_escape);
5871 if (ch == EOF) {
5872 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005873
5874 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005875 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005876 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005877 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005878 /* end_trigger == '}' case errors out earlier,
5879 * checking only ')' */
5880 if (end_trigger == ')') {
5881 syntax_error_unterm_ch('('); /* exits */
5882 /* goto parse_error; */
5883 }
5884
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005885 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005886 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005887 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005888 o_free(&dest);
5889 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005890 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005891 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005892 /* (this makes bare "&" cmd a no-op.
5893 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005894 if (pi->num_cmds == 0
5895 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5896 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005897 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005898 pi = NULL;
5899 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005900#if !BB_MMU
5901 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5902 if (pstring)
5903 *pstring = ctx.as_string.data;
5904 else
5905 o_free_unsafe(&ctx.as_string);
5906#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005907 debug_leave();
5908 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005909 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005910 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005911 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005912 is_ifs = strchr(G.ifs, ch);
5913 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005914 "\\$\"" IF_HUSH_TICK("`") /* always special */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005915 , ch);
5916
5917 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005918 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005919 o_addQchr(&dest, ch);
5920 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5921 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005922 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005923 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005924 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005925 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005926 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005927 continue;
5928 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005929
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005930 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005931 if (done_word(&dest, &ctx)) {
5932 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005933 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005934 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00005935#if ENABLE_HUSH_CASE
5936 /* "case ... in <newline> word) ..." -
5937 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005938 if (ctx.command->argv == NULL
5939 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00005940 ) {
5941 continue;
5942 }
5943#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005944 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005945 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005946 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5947 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005948 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005949 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005950 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005951 heredoc_cnt = 0;
5952 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005953 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005954 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00005955 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005956 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005957 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005958 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005959
5960 /* "cmd}" or "cmd }..." without semicolon or &:
5961 * } is an ordinary char in this case, even inside { cmd; }
5962 * Pathological example: { ""}; } should exec "}" cmd
5963 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005964 if (ch == '}') {
5965 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5966 || dest.length != 0 /* word} */
5967 || dest.o_quoted /* ""} */
5968 ) {
5969 goto ordinary_char;
5970 }
5971 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5972 goto skip_end_trigger;
5973 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005974 }
5975
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005976 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005977 && (ch != ';' || heredoc_cnt == 0)
5978#if ENABLE_HUSH_CASE
5979 && (ch != ')'
5980 || ctx.ctx_res_w != RES_MATCH
5981 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5982 )
5983#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005984 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005985 if (heredoc_cnt) {
5986 /* This is technically valid:
5987 * { cat <<HERE; }; echo Ok
5988 * heredoc
5989 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005990 * HERE
5991 * but we don't support this.
5992 * We require heredoc to be in enclosing {}/(),
5993 * if any.
5994 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005995 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005996 goto parse_error;
5997 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005998 if (done_word(&dest, &ctx)) {
5999 goto parse_error;
6000 }
6001 done_pipe(&ctx, PIPE_SEQ);
6002 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006003 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006004 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006005 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006006 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006007 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006008#if !BB_MMU
6009 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6010 if (pstring)
6011 *pstring = ctx.as_string.data;
6012 else
6013 o_free_unsafe(&ctx.as_string);
6014#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006015 debug_leave();
6016 debug_printf_parse("parse_stream return %p: "
6017 "end_trigger char found\n",
6018 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006019 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006020 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006021 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006022 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006023 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006024 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006025
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006026 next = '\0';
6027 if (ch != '\n') {
6028 next = i_peek(input);
6029 }
6030
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006031 /* Catch <, > before deciding whether this word is
6032 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6033 switch (ch) {
6034 case '>':
6035 redir_fd = redirect_opt_num(&dest);
6036 if (done_word(&dest, &ctx)) {
6037 goto parse_error;
6038 }
6039 redir_style = REDIRECT_OVERWRITE;
6040 if (next == '>') {
6041 redir_style = REDIRECT_APPEND;
6042 ch = i_getch(input);
6043 nommu_addchr(&ctx.as_string, ch);
6044 }
6045#if 0
6046 else if (next == '(') {
6047 syntax_error(">(process) not supported");
6048 goto parse_error;
6049 }
6050#endif
6051 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6052 goto parse_error;
6053 continue; /* back to top of while (1) */
6054 case '<':
6055 redir_fd = redirect_opt_num(&dest);
6056 if (done_word(&dest, &ctx)) {
6057 goto parse_error;
6058 }
6059 redir_style = REDIRECT_INPUT;
6060 if (next == '<') {
6061 redir_style = REDIRECT_HEREDOC;
6062 heredoc_cnt++;
6063 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6064 ch = i_getch(input);
6065 nommu_addchr(&ctx.as_string, ch);
6066 } else if (next == '>') {
6067 redir_style = REDIRECT_IO;
6068 ch = i_getch(input);
6069 nommu_addchr(&ctx.as_string, ch);
6070 }
6071#if 0
6072 else if (next == '(') {
6073 syntax_error("<(process) not supported");
6074 goto parse_error;
6075 }
6076#endif
6077 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6078 goto parse_error;
6079 continue; /* back to top of while (1) */
6080 }
6081
6082 if (dest.o_assignment == MAYBE_ASSIGNMENT
6083 /* check that we are not in word in "a=1 2>word b=1": */
6084 && !ctx.pending_redirect
6085 ) {
6086 /* ch is a special char and thus this word
6087 * cannot be an assignment */
6088 dest.o_assignment = NOT_ASSIGNMENT;
6089 }
6090
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006091 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6092
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006093 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006094 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006095 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006096 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006097 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006098 if (ch == EOF || ch == '\n')
6099 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006100 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006101 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006102 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006103 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006104 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006105 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006106 }
6107 break;
6108 case '\\':
6109 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006110 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006111 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006112 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006113 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006114 if (ch != '\n') {
6115 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006116 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006117 o_addchr(&dest, ch);
6118 nommu_addchr(&ctx.as_string, ch);
6119 /* Example: echo Hello \2>file
6120 * we need to know that word 2 is quoted */
6121 dest.o_quoted = 1;
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006122 } else {
6123#if !BB_MMU
6124 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6125 ctx.as_string.data[--ctx.as_string.length] = '\0';
6126#endif
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006127 }
Eric Andersen25f27032001-04-26 23:22:31 +00006128 break;
6129 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006130 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006131 debug_printf_parse("parse_stream parse error: "
6132 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006133 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006134 }
Eric Andersen25f27032001-04-26 23:22:31 +00006135 break;
6136 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006137 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006138 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006139 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006140 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006141 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006142 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006143 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006144 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006145 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006146 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006147 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006148 }
Eric Andersen25f27032001-04-26 23:22:31 +00006149 break;
6150 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006151 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006152 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006153 if (dest.o_assignment == NOT_ASSIGNMENT)
6154 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006155 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006156#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006157 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006158#if !BB_MMU
6159 int pos;
6160#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006161 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6162 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006163#if !BB_MMU
6164 pos = dest.length;
6165#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006166 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006167#if !BB_MMU
6168 o_addstr(&ctx.as_string, dest.data + pos);
6169 o_addchr(&ctx.as_string, '`');
6170#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006171 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6172 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006173 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006174 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006175#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006176 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006177#if ENABLE_HUSH_CASE
6178 case_semi:
6179#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006180 if (done_word(&dest, &ctx)) {
6181 goto parse_error;
6182 }
6183 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006184#if ENABLE_HUSH_CASE
6185 /* Eat multiple semicolons, detect
6186 * whether it means something special */
6187 while (1) {
6188 ch = i_peek(input);
6189 if (ch != ';')
6190 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006191 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006192 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006193 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006194 ctx.ctx_dsemicolon = 1;
6195 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006196 break;
6197 }
6198 }
6199#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006200 new_cmd:
6201 /* We just finished a cmd. New one may start
6202 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006203 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006204 break;
6205 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006206 if (done_word(&dest, &ctx)) {
6207 goto parse_error;
6208 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006209 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006210 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006211 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006212 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006213 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006214 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006215 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006216 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006217 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006218 if (done_word(&dest, &ctx)) {
6219 goto parse_error;
6220 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006221#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006222 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006223 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006224#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006225 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006226 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006227 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006228 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006229 } else {
6230 /* we could pick up a file descriptor choice here
6231 * with redirect_opt_num(), but bash doesn't do it.
6232 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006233 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00006234 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006235 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006236 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006237#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006238 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006239 if (ctx.ctx_res_w == RES_MATCH
6240 && ctx.command->argv == NULL /* not (word|(... */
6241 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006242 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006243 ) {
6244 continue;
6245 }
6246#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006247 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006248 if (parse_group(&dest, &ctx, input, ch) != 0) {
6249 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006250 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006251 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006252 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006253#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006254 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006255 goto case_semi;
6256#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006257 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006258 /* proper use of this character is caught by end_trigger:
6259 * if we see {, we call parse_group(..., end_trigger='}')
6260 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006261 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006262 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006263 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006264 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006265 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006266 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006267 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006268
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006269 parse_error:
6270 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006271 struct parse_context *pctx;
6272 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006273
6274 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006275 * Sample for finding leaks on syntax error recovery path.
6276 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006277 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006278 * Samples to catch leaks at execution:
6279 * while if (true | {true;}); then echo ok; fi; do break; done
6280 * 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 +00006281 */
6282 pctx = &ctx;
6283 do {
6284 /* Update pipe/command counts,
6285 * otherwise freeing may miss some */
6286 done_pipe(pctx, PIPE_SEQ);
6287 debug_printf_clean("freeing list %p from ctx %p\n",
6288 pctx->list_head, pctx);
6289 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006290 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006291 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006292#if !BB_MMU
6293 o_free_unsafe(&pctx->as_string);
6294#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006295 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006296 if (pctx != &ctx) {
6297 free(pctx);
6298 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006299 IF_HAS_KEYWORDS(pctx = p2;)
6300 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006301 /* Free text, clear all dest fields */
6302 o_free(&dest);
6303 /* If we are not in top-level parse, we return,
6304 * our caller will propagate error.
6305 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006306 if (end_trigger != ';') {
6307#if !BB_MMU
6308 if (pstring)
6309 *pstring = NULL;
6310#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006311 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006312 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006313 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006314 /* Discard cached input, force prompt */
6315 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006316 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006317 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006318 }
Eric Andersen25f27032001-04-26 23:22:31 +00006319}
6320
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006321/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006322 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6323 * end_trigger controls how often we stop parsing
6324 * NUL: parse all, execute, return
6325 * ';': parse till ';' or newline, execute, repeat till EOF
6326 */
6327static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006328{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006329 while (1) {
6330 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006331
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006332 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006333 if (!pipe_list) /* EOF */
6334 break;
6335 debug_print_tree(pipe_list, 0);
6336 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6337 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006338 }
Eric Andersen25f27032001-04-26 23:22:31 +00006339}
6340
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006341static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006342{
6343 struct in_str input;
6344 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006345 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006346}
6347
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006348static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006349{
Eric Andersen25f27032001-04-26 23:22:31 +00006350 struct in_str input;
6351 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006352 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006353}
6354
Denis Vlasenkof9375282009-04-05 19:13:39 +00006355/* Called a few times only (or even once if "sh -c") */
6356static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006357{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006358 unsigned sig;
6359 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006360
Denis Vlasenkof9375282009-04-05 19:13:39 +00006361 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006362 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006363 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006364 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006365 mask |= SPECIAL_JOB_SIGS;
6366 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006367 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006368
Denis Vlasenkof9375282009-04-05 19:13:39 +00006369 if (!second_time)
6370 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6371 sig = 0;
6372 while (mask) {
6373 if (mask & 1)
6374 sigaddset(&G.blocked_set, sig);
6375 mask >>= 1;
6376 sig++;
6377 }
6378 sigdelset(&G.blocked_set, SIGCHLD);
6379
6380 sigprocmask(SIG_SETMASK, &G.blocked_set,
6381 second_time ? NULL : &G.inherited_set);
6382 /* POSIX allows shell to re-enable SIGCHLD
6383 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006384#if ENABLE_HUSH_FAST
6385 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006386 if (!second_time)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006387 signal(SIGCHLD, SIGCHLD_handler);
6388#else
6389 if (!second_time)
6390 signal(SIGCHLD, SIG_DFL);
6391#endif
Denis Vlasenkof9375282009-04-05 19:13:39 +00006392}
6393
6394#if ENABLE_HUSH_JOB
6395/* helper */
6396static void maybe_set_to_sigexit(int sig)
6397{
6398 void (*handler)(int);
6399 /* non_DFL_mask'ed signals are, well, masked,
6400 * no need to set handler for them.
6401 */
6402 if (!((G.non_DFL_mask >> sig) & 1)) {
6403 handler = signal(sig, sigexit);
6404 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6405 signal(sig, handler);
6406 }
6407}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006408/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006409static void set_fatal_handlers(void)
6410{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006411 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006412 if (HUSH_DEBUG) {
6413 maybe_set_to_sigexit(SIGILL );
6414 maybe_set_to_sigexit(SIGFPE );
6415 maybe_set_to_sigexit(SIGBUS );
6416 maybe_set_to_sigexit(SIGSEGV);
6417 maybe_set_to_sigexit(SIGTRAP);
6418 } /* else: hush is perfect. what SEGV? */
6419 maybe_set_to_sigexit(SIGABRT);
6420 /* bash 3.2 seems to handle these just like 'fatal' ones */
6421 maybe_set_to_sigexit(SIGPIPE);
6422 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006423 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006424 * if we aren't interactive... but in this case
6425 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006426 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006427 /*maybe_set_to_sigexit(SIGTERM);*/
6428 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006429}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006430#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006431
Denis Vlasenkod5762932009-03-31 11:22:57 +00006432static int set_mode(const char cstate, const char mode)
6433{
6434 int state = (cstate == '-' ? 1 : 0);
6435 switch (mode) {
6436 case 'n': G.fake_mode = state; break;
6437 case 'x': /*G.debug_mode = state;*/ break;
6438 default: return EXIT_FAILURE;
6439 }
6440 return EXIT_SUCCESS;
6441}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006442
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006443int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006444int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006445{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006446 static const struct variable const_shell_ver = {
6447 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006448 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006449 .max_len = 1, /* 0 can provoke free(name) */
6450 .flg_export = 1,
6451 .flg_read_only = 1,
6452 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00006453 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00006454 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006455 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006456 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006457 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006458
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006459 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006460 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006461 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006462#if !BB_MMU
6463 G.argv0_for_re_execing = argv[0];
6464#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006465 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006466 G.shell_ver = const_shell_ver; /* copying struct here */
6467 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006468 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006469 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6470 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006471 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006472 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006473 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006474 if (e) while (*e) {
6475 char *value = strchr(*e, '=');
6476 if (value) { /* paranoia */
6477 cur_var->next = xzalloc(sizeof(*cur_var));
6478 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006479 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006480 cur_var->max_len = strlen(*e);
6481 cur_var->flg_export = 1;
6482 }
6483 e++;
6484 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006485 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006486 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02006487 putenv((char *)hush_version_str);
6488
6489 /* Export PWD */
6490 set_pwd_var(/*exp:*/ 1);
6491 /* bash also exports SHLVL and _,
6492 * and sets (but doesn't export) the following variables:
6493 * BASH=/bin/bash
6494 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6495 * BASH_VERSION='3.2.0(1)-release'
6496 * HOSTTYPE=i386
6497 * MACHTYPE=i386-pc-linux-gnu
6498 * OSTYPE=linux-gnu
6499 * HOSTNAME=<xxxxxxxxxx>
6500 * PPID=<NNNNN>
6501 * EUID=<NNNNN>
6502 * UID=<NNNNN>
6503 * GROUPS=()
6504 * LINES=<NNN>
6505 * COLUMNS=<NNN>
6506 * BASH_ARGC=()
6507 * BASH_ARGV=()
6508 * BASH_LINENO=()
6509 * BASH_SOURCE=()
6510 * DIRSTACK=()
6511 * PIPESTATUS=([0]="0")
6512 * HISTFILE=/<xxx>/.bash_history
6513 * HISTFILESIZE=500
6514 * HISTSIZE=500
6515 * MAILCHECK=60
6516 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6517 * SHELL=/bin/bash
6518 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6519 * TERM=dumb
6520 * OPTERR=1
6521 * OPTIND=1
6522 * IFS=$' \t\n'
6523 * PS1='\s-\v\$ '
6524 * PS2='> '
6525 * PS4='+ '
6526 */
6527
Denis Vlasenko38f63192007-01-22 09:03:07 +00006528#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006529 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006530#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006531 G.global_argc = argc;
6532 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006533 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006534 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006535
Denis Vlasenkoed782372009-04-10 00:45:02 +00006536 if (setjmp(die_jmp)) {
6537 /* xfunc has failed! die die die */
6538 /* no EXIT traps, this is an escape hatch! */
6539 G.exiting = 1;
6540 hush_exit(xfunc_error_retval);
6541 }
6542
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006543 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006544 * block_signals(0) if we are going to execute "sh <script>",
6545 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006546 * If we later decide that we are interactive, we run block_signals(0)
6547 * (or re-run block_signals(1) if we ran block_signals(0) before)
6548 * in order to intercept (more) signals.
6549 */
6550
6551 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006552 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006553 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006554 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02006555 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006556#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006557 "<:$:R:V:"
6558# if ENABLE_HUSH_FUNCTIONS
6559 "F:"
6560# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006561#endif
6562 );
6563 if (opt <= 0)
6564 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006565 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006566 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006567 /* Possibilities:
6568 * sh ... -c 'script'
6569 * sh ... -c 'script' ARG0 [ARG1...]
6570 * On NOMMU, if builtin_argc != 0,
6571 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6572 * "" needs to be replaced with NULL
6573 * and BARGV vector fed to builtin function.
6574 * Note: this form never happens:
6575 * sh ... -c 'builtin' [BARGV...] ""
6576 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006577 if (!G.root_pid)
6578 G.root_pid = getpid();
Denis Vlasenko87a86552008-07-29 19:43:10 +00006579 G.global_argv = argv + optind;
6580 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006581 if (builtin_argc) {
6582 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6583 const struct built_in_command *x;
6584
6585 block_signals(0); /* 0: called 1st time */
6586 x = find_builtin(optarg);
6587 if (x) { /* paranoia */
6588 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6589 G.global_argv += builtin_argc;
6590 G.global_argv[-1] = NULL; /* replace "" */
6591 G.last_exitcode = x->function(argv + optind - 1);
6592 }
6593 goto final_return;
6594 }
6595 if (!G.global_argv[0]) {
6596 /* -c 'script' (no params): prevent empty $0 */
6597 G.global_argv--; /* points to argv[i] of 'script' */
6598 G.global_argv[0] = argv[0];
6599 G.global_argc--;
6600 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006601 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006602 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006603 goto final_return;
6604 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00006605 /* Well, we cannot just declare interactiveness,
6606 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006607 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006608 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006609 case 's':
6610 /* "-s" means "read from stdin", but this is how we always
6611 * operate, so simply do nothing here. */
6612 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006613#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00006614 case '<': /* "big heredoc" support */
6615 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6616 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006617 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006618 G.root_pid = bb_strtou(optarg, &optarg, 16);
6619 optarg++;
6620 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6621 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006622 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006623 optarg++;
6624 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006625# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006626 optarg++;
6627 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006628# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006629 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006630 case 'R':
6631 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02006632 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006633 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00006634# if ENABLE_HUSH_FUNCTIONS
6635 case 'F': {
6636 struct function *funcp = new_function(optarg);
6637 /* funcp->name is already set to optarg */
6638 /* funcp->body is set to NULL. It's a special case. */
6639 funcp->body_as_string = argv[optind];
6640 optind++;
6641 break;
6642 }
6643# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006644#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006645 case 'n':
6646 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00006647 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006648 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006649 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006650#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006651 fprintf(stderr, "Usage: sh [FILE]...\n"
6652 " or: sh -c command [args]...\n\n");
6653 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006654#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006655 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006656#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006657 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006658 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006659
6660 if (!G.root_pid)
6661 G.root_pid = getpid();
Denis Vlasenkof9375282009-04-05 19:13:39 +00006662
6663 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006664 if (argv[0] && argv[0][0] == '-') {
6665 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006666 debug_printf("sourcing /etc/profile\n");
6667 input = fopen_for_read("/etc/profile");
6668 if (input != NULL) {
6669 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00006670 block_signals(0); /* 0: called 1st time */
6671 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006672 parse_and_run_file(input);
6673 fclose(input);
6674 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006675 /* bash: after sourcing /etc/profile,
6676 * tries to source (in the given order):
6677 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006678 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006679 * bash also sources ~/.bash_logout on exit.
6680 * If called as sh, skips .bash_XXX files.
6681 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006682 }
6683
Denis Vlasenkof9375282009-04-05 19:13:39 +00006684 if (argv[optind]) {
6685 FILE *input;
6686 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006687 * "bash <script>" (which is never interactive (unless -i?))
6688 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00006689 * If called as sh, does the same but with $ENV.
6690 */
6691 debug_printf("running script '%s'\n", argv[optind]);
6692 G.global_argv = argv + optind;
6693 G.global_argc = argc - optind;
6694 input = xfopen_for_read(argv[optind]);
6695 close_on_exec_on(fileno(input));
6696 if (!signal_mask_is_inited)
6697 block_signals(0); /* 0: called 1st time */
6698 parse_and_run_file(input);
6699#if ENABLE_FEATURE_CLEAN_UP
6700 fclose(input);
6701#endif
6702 goto final_return;
6703 }
6704
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006705 /* Up to here, shell was non-interactive. Now it may become one.
6706 * NB: don't forget to (re)run block_signals(0/1) as needed.
6707 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006708
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006709 /* A shell is interactive if the '-i' flag was given,
6710 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00006711 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00006712 * no arguments remaining or the -s flag given
6713 * standard input is a terminal
6714 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00006715 * Refer to Posix.2, the description of the 'sh' utility.
6716 */
6717#if ENABLE_HUSH_JOB
6718 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04006719 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6720 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6721 if (G_saved_tty_pgrp < 0)
6722 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006723
6724 /* try to dup stdin to high fd#, >= 255 */
6725 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6726 if (G_interactive_fd < 0) {
6727 /* try to dup to any fd */
6728 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006729 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006730 /* give up */
6731 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04006732 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006733 }
6734 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006735// TODO: track & disallow any attempts of user
6736// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00006737 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006738 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006739 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006740 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006741
Mike Frysinger38478a62009-05-20 04:48:06 -04006742 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006743 /* If we were run as 'hush &', sleep until we are
6744 * in the foreground (tty pgrp == our pgrp).
6745 * If we get started under a job aware app (like bash),
6746 * make sure we are now in charge so we don't fight over
6747 * who gets the foreground */
6748 while (1) {
6749 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04006750 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6751 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006752 break;
6753 /* send TTIN to ourself (should stop us) */
6754 kill(- shell_pgrp, SIGTTIN);
6755 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006756 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006757
Denis Vlasenkof9375282009-04-05 19:13:39 +00006758 /* Block some signals */
6759 block_signals(signal_mask_is_inited);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006760
Mike Frysinger38478a62009-05-20 04:48:06 -04006761 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006762 /* Set other signals to restore saved_tty_pgrp */
6763 set_fatal_handlers();
6764 /* Put ourselves in our own process group
6765 * (bash, too, does this only if ctty is available) */
6766 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6767 /* Grab control of the terminal */
6768 tcsetpgrp(G_interactive_fd, getpid());
6769 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00006770 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00006771 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006772 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006773 } else if (!signal_mask_is_inited) {
6774 block_signals(0); /* 0: called 1st time */
6775 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006776#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00006777 /* No job control compiled in, only prompt/line editing */
6778 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006779 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6780 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006781 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006782 G_interactive_fd = dup(STDIN_FILENO);
6783 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006784 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006785 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006786 }
6787 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006788 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006789 close_on_exec_on(G_interactive_fd);
6790 block_signals(signal_mask_is_inited);
6791 } else if (!signal_mask_is_inited) {
6792 block_signals(0);
6793 }
6794#else
6795 /* We have interactiveness code disabled */
6796 if (!signal_mask_is_inited) {
6797 block_signals(0);
6798 }
6799#endif
6800 /* bash:
6801 * if interactive but not a login shell, sources ~/.bashrc
6802 * (--norc turns this off, --rcfile <file> overrides)
6803 */
6804
6805 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Mike Frysinger258275d2009-04-05 21:19:43 +00006806 printf("\n\n%s hush - the humble shell\n", bb_banner);
Mike Frysinger26cf2832009-04-24 06:40:30 +00006807 if (ENABLE_HUSH_HELP)
6808 puts("Enter 'help' for a list of built-in commands.");
6809 puts("");
Mike Frysingerb2705e12009-03-23 08:44:02 +00006810 }
6811
Denis Vlasenkof9375282009-04-05 19:13:39 +00006812 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00006813
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006814 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00006815#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00006816 if (G.cwd != bb_msg_unknown)
6817 free((char*)G.cwd);
6818 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006819 while (cur_var) {
6820 struct variable *tmp = cur_var;
6821 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006822 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006823 cur_var = cur_var->next;
6824 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00006825 }
Eric Andersen25f27032001-04-26 23:22:31 +00006826#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006827 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00006828}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006829
6830
6831#if ENABLE_LASH
6832int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6833int lash_main(int argc, char **argv)
6834{
Denys Vlasenko07934912009-08-20 03:40:04 +02006835 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006836 return hush_main(argc, argv);
6837}
6838#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006839
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02006840#if ENABLE_MSH
6841int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6842int msh_main(int argc, char **argv)
6843{
6844 //bb_error_msg("msh is deprecated, please use hush instead");
6845 return hush_main(argc, argv);
6846}
6847#endif
6848
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006849
6850/*
6851 * Built-ins
6852 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006853static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006854{
6855 return 0;
6856}
6857
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006858static int FAST_FUNC builtin_test(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006859{
6860 int argc = 0;
6861 while (*argv) {
6862 argc++;
6863 argv++;
6864 }
6865 return test_main(argc, argv - argc);
6866}
6867
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006868static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006869{
6870 int argc = 0;
6871 while (*argv) {
6872 argc++;
6873 argv++;
6874 }
6875 return echo_main(argc, argv - argc);
6876}
6877
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006878static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006879{
6880 int rcode = EXIT_SUCCESS;
6881
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006882 if (*++argv) {
6883 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006884 /* bash:
6885 * eval "echo Hi; done" ("done" is syntax error):
6886 * "echo Hi" will not execute too.
6887 */
6888 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006889 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006890 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006891 }
6892 return rcode;
6893}
6894
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006895static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006896{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006897 const char *newdir = argv[1];
6898 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006899 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006900 * bash says "bash: cd: HOME not set" and does nothing
6901 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006902 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02006903 const char *home = get_local_var_value("HOME");
6904 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006905 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006906 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006907 /* Mimic bash message exactly */
6908 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006909 return EXIT_FAILURE;
6910 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006911 /* Read current dir (get_cwd(1) is inside) and set PWD.
6912 * Note: do not enforce exporting. If PWD was unset or unexported,
6913 * set it again, but do not export. bash does the same.
6914 */
6915 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006916 return EXIT_SUCCESS;
6917}
6918
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006919static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006920{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006921 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006922 return EXIT_SUCCESS; /* bash does this */
6923 {
6924#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006925 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006926#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006927 /* TODO: if exec fails, bash does NOT exit! We do... */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006928 pseudo_exec_argv(&dummy, argv, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006929 /* never returns */
6930 }
6931}
6932
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006933static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006934{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00006935 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00006936
6937 /* interactive bash:
6938 * # trap "echo EEE" EXIT
6939 * # exit
6940 * exit
6941 * There are stopped jobs.
6942 * (if there are _stopped_ jobs, running ones don't count)
6943 * # exit
6944 * exit
6945 # EEE (then bash exits)
6946 *
6947 * we can use G.exiting = -1 as indicator "last cmd was exit"
6948 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00006949
6950 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006951 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006952 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006953 /* mimic bash: exit 123abc == exit 255 + error msg */
6954 xfunc_error_retval = 255;
6955 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006956 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006957}
6958
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006959static void print_escaped(const char *s)
6960{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006961 if (*s == '\'')
6962 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006963 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006964 const char *p = strchrnul(s, '\'');
6965 /* print 'xxxx', possibly just '' */
6966 printf("'%.*s'", (int)(p - s), s);
6967 if (*p == '\0')
6968 break;
6969 s = p;
6970 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006971 /* s points to '; print "'''...'''" */
6972 putchar('"');
6973 do putchar('\''); while (*++s == '\'');
6974 putchar('"');
6975 } while (*s);
6976}
6977
Denys Vlasenko295fef82009-06-03 12:47:26 +02006978#if !ENABLE_HUSH_LOCAL
6979#define helper_export_local(argv, exp, lvl) \
6980 helper_export_local(argv, exp)
6981#endif
6982static void helper_export_local(char **argv, int exp, int lvl)
6983{
6984 do {
6985 char *name = *argv;
6986
6987 /* So far we do not check that name is valid (TODO?) */
6988
6989 if (strchr(name, '=') == NULL) {
6990 struct variable *var;
6991
6992 var = get_local_var(name);
6993 if (exp == -1) { /* unexporting? */
6994 /* export -n NAME (without =VALUE) */
6995 if (var) {
6996 var->flg_export = 0;
6997 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6998 unsetenv(name);
6999 } /* else: export -n NOT_EXISTING_VAR: no-op */
7000 continue;
7001 }
7002 if (exp == 1) { /* exporting? */
7003 /* export NAME (without =VALUE) */
7004 if (var) {
7005 var->flg_export = 1;
7006 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7007 putenv(var->varstr);
7008 continue;
7009 }
7010 }
7011 /* Exporting non-existing variable.
7012 * bash does not put it in environment,
7013 * but remembers that it is exported,
7014 * and does put it in env when it is set later.
7015 * We just set it to "" and export. */
7016 /* Or, it's "local NAME" (without =VALUE).
7017 * bash sets the value to "". */
7018 name = xasprintf("%s=", name);
7019 } else {
7020 /* (Un)exporting/making local NAME=VALUE */
7021 name = xstrdup(name);
7022 }
7023 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7024 } while (*++argv);
7025}
7026
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007027static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007028{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007029 unsigned opt_unexport;
7030
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007031#if ENABLE_HUSH_EXPORT_N
7032 /* "!": do not abort on errors */
7033 opt_unexport = getopt32(argv, "!n");
7034 if (opt_unexport == (uint32_t)-1)
7035 return EXIT_FAILURE;
7036 argv += optind;
7037#else
7038 opt_unexport = 0;
7039 argv++;
7040#endif
7041
7042 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007043 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007044 if (e) {
7045 while (*e) {
7046#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007047 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007048#else
7049 /* ash emits: export VAR='VAL'
7050 * bash: declare -x VAR="VAL"
7051 * we follow ash example */
7052 const char *s = *e++;
7053 const char *p = strchr(s, '=');
7054
7055 if (!p) /* wtf? take next variable */
7056 continue;
7057 /* export var= */
7058 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007059 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007060 putchar('\n');
7061#endif
7062 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007063 /*fflush(stdout); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007064 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007065 return EXIT_SUCCESS;
7066 }
7067
Denys Vlasenko295fef82009-06-03 12:47:26 +02007068 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007069
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007070 return EXIT_SUCCESS;
7071}
7072
Denys Vlasenko295fef82009-06-03 12:47:26 +02007073#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007074static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007075{
7076 if (G.func_nest_level == 0) {
7077 bb_error_msg("%s: not in a function", argv[0]);
7078 return EXIT_FAILURE; /* bash compat */
7079 }
7080 helper_export_local(argv, 0, G.func_nest_level);
7081 return EXIT_SUCCESS;
7082}
7083#endif
7084
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007085static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007086{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007087 int sig;
7088 char *new_cmd;
7089
7090 if (!G.traps)
7091 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7092
7093 argv++;
7094 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007095 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007096 /* No args: print all trapped */
7097 for (i = 0; i < NSIG; ++i) {
7098 if (G.traps[i]) {
7099 printf("trap -- ");
7100 print_escaped(G.traps[i]);
Denys Vlasenko91836ba2009-09-23 01:46:19 +02007101 /* bash compat: it says SIGxxx, not just xxx */
Denys Vlasenko2f7894b2009-09-24 01:43:21 +02007102 printf(" %s%s\n", i == 0 ? "" : "SIG", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007103 }
7104 }
7105 /*fflush(stdout); - done after each builtin anyway */
7106 return EXIT_SUCCESS;
7107 }
7108
7109 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007110 /* If first arg is a number: reset all specified signals */
7111 sig = bb_strtou(*argv, NULL, 10);
7112 if (errno == 0) {
7113 int ret;
7114 process_sig_list:
7115 ret = EXIT_SUCCESS;
7116 while (*argv) {
7117 sig = get_signum(*argv++);
7118 if (sig < 0 || sig >= NSIG) {
7119 ret = EXIT_FAILURE;
7120 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007121 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007122 continue;
7123 }
7124
7125 free(G.traps[sig]);
7126 G.traps[sig] = xstrdup(new_cmd);
7127
7128 debug_printf("trap: setting SIG%s (%i) to '%s'",
7129 get_signame(sig), sig, G.traps[sig]);
7130
7131 /* There is no signal for 0 (EXIT) */
7132 if (sig == 0)
7133 continue;
7134
7135 if (new_cmd) {
7136 sigaddset(&G.blocked_set, sig);
7137 } else {
7138 /* There was a trap handler, we are removing it
7139 * (if sig has non-DFL handling,
7140 * we don't need to do anything) */
7141 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7142 continue;
7143 sigdelset(&G.blocked_set, sig);
7144 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007145 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007146 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007147 return ret;
7148 }
7149
7150 if (!argv[1]) { /* no second arg */
7151 bb_error_msg("trap: invalid arguments");
7152 return EXIT_FAILURE;
7153 }
7154
7155 /* First arg is "-": reset all specified to default */
7156 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7157 /* Everything else: set arg as signal handler
7158 * (includes "" case, which ignores signal) */
7159 if (argv[0][0] == '-') {
7160 if (argv[0][1] == '\0') { /* "-" */
7161 /* new_cmd remains NULL: "reset these sigs" */
7162 goto reset_traps;
7163 }
7164 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7165 argv++;
7166 }
7167 /* else: "-something", no special meaning */
7168 }
7169 new_cmd = *argv;
7170 reset_traps:
7171 argv++;
7172 goto process_sig_list;
7173}
7174
Mike Frysinger93cadc22009-05-27 17:06:25 -04007175/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007176static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007177{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007178 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007179
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007180 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007181 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007182 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007183
7184 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007185 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007186 type = "an alias";*/
7187#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007188 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007189 type = "a function";
7190#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007191 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007192 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007193 else if ((path = find_in_path(*argv)) != NULL)
7194 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007195 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007196 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007197 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007198 continue;
7199 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007200
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007201 printf("%s is %s\n", *argv, type);
7202 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007203 }
7204
7205 return ret;
7206}
7207
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007208#if ENABLE_HUSH_JOB
7209/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007210static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007211{
7212 int i, jobnum;
7213 struct pipe *pi;
7214
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007215 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007216 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007217
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007218 /* If they gave us no args, assume they want the last backgrounded task */
7219 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007220 for (pi = G.job_list; pi; pi = pi->next) {
7221 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007222 goto found;
7223 }
7224 }
7225 bb_error_msg("%s: no current job", argv[0]);
7226 return EXIT_FAILURE;
7227 }
7228 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7229 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7230 return EXIT_FAILURE;
7231 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007232 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007233 if (pi->jobid == jobnum) {
7234 goto found;
7235 }
7236 }
7237 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7238 return EXIT_FAILURE;
7239 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007240 /* TODO: bash prints a string representation
7241 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007242 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007243 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007244 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007245 }
7246
7247 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007248 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7249 for (i = 0; i < pi->num_cmds; i++) {
7250 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7251 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007252 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007253 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007254
7255 i = kill(- pi->pgrp, SIGCONT);
7256 if (i < 0) {
7257 if (errno == ESRCH) {
7258 delete_finished_bg_job(pi);
7259 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007260 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007261 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007262 }
7263
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007264 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007265 remove_bg_job(pi);
7266 return checkjobs_and_fg_shell(pi);
7267 }
7268 return EXIT_SUCCESS;
7269}
7270#endif
7271
7272#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007273static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007274{
7275 const struct built_in_command *x;
7276
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007277 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007278 "Built-in commands:\n"
7279 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007280 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7281 if (x->descr)
7282 printf("%s\t%s\n", x->cmd, x->descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007283 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007284 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007285 return EXIT_SUCCESS;
7286}
7287#endif
7288
7289#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007290static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007291{
7292 struct pipe *job;
7293 const char *status_string;
7294
Denis Vlasenko87a86552008-07-29 19:43:10 +00007295 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007296 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007297 status_string = "Stopped";
7298 else
7299 status_string = "Running";
7300
7301 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7302 }
7303 return EXIT_SUCCESS;
7304}
7305#endif
7306
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007307#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007308static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007309{
7310 void *p;
7311 unsigned long l;
7312
Denys Vlasenko27726cb2009-09-12 14:48:33 +02007313#ifdef M_TRIM_THRESHOLD
7314 /* Optional. Reduces probability of false positives */
7315 malloc_trim(0);
7316#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007317 /* Crude attempt to find where "free memory" starts,
7318 * sans fragmentation. */
7319 p = malloc(240);
7320 l = (unsigned long)p;
7321 free(p);
7322 p = malloc(3400);
7323 if (l < (unsigned long)p) l = (unsigned long)p;
7324 free(p);
7325
7326 if (!G.memleak_value)
7327 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007328
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007329 l -= G.memleak_value;
7330 if ((long)l < 0)
7331 l = 0;
7332 l /= 1024;
7333 if (l > 127)
7334 l = 127;
7335
7336 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7337 return l;
7338}
7339#endif
7340
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007341static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007342{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007343 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007344 return EXIT_SUCCESS;
7345}
7346
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007347static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007348{
7349 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007350 const char *name = "REPLY";
7351
7352 if (argv[1]) {
7353 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007354 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7355 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007356 if (!is_well_formed_var_name(name, '\0')) {
7357 /* Mimic bash message */
7358 bb_error_msg("read: '%s': not a valid identifier", name);
7359 return 1;
7360 }
7361 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007362
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007363//TODO: bash unbackslashes input, splits words and puts them in argv[i]
7364
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007365 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denys Vlasenko295fef82009-06-03 12:47:26 +02007366 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007367}
7368
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007369/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7370 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007371 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007372 * set [-abCefhmnuvx] [-o option] [argument...]
7373 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007374 * set -- [argument...]
7375 * set -o
7376 * set +o
7377 * Implementations shall support the options in both their hyphen and
7378 * plus-sign forms. These options can also be specified as options to sh.
7379 * Examples:
7380 * Write out all variables and their values: set
7381 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7382 * Turn on the -x and -v options: set -xv
7383 * Unset all positional parameters: set --
7384 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7385 * Set the positional parameters to the expansion of x, even if x expands
7386 * with a leading '-' or '+': set -- $x
7387 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007388 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007389 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007390static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007391{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007392 int n;
7393 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007394 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007395
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007396 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007397 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007398 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007399 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007400 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007401 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007402
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007403 do {
7404 if (!strcmp(arg, "--")) {
7405 ++argv;
7406 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007407 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00007408 if (arg[0] != '+' && arg[0] != '-')
7409 break;
7410 for (n = 1; arg[n]; ++n)
7411 if (set_mode(arg[0], arg[n]))
7412 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007413 } while ((arg = *++argv) != NULL);
7414 /* Now argv[0] is 1st argument */
7415
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007416 if (arg == NULL)
7417 return EXIT_SUCCESS;
7418 set_argv:
7419
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007420 /* NB: G.global_argv[0] ($0) is never freed/changed */
7421 g_argv = G.global_argv;
7422 if (G.global_args_malloced) {
7423 pp = g_argv;
7424 while (*++pp)
7425 free(*pp);
7426 g_argv[1] = NULL;
7427 } else {
7428 G.global_args_malloced = 1;
7429 pp = xzalloc(sizeof(pp[0]) * 2);
7430 pp[0] = g_argv[0]; /* retain $0 */
7431 g_argv = pp;
7432 }
7433 /* This realloc's G.global_argv */
7434 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7435
7436 n = 1;
7437 while (*++pp)
7438 n++;
7439 G.global_argc = n;
7440
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007441 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007442
7443 /* Nothing known, so abort */
7444 error:
7445 bb_error_msg("set: %s: invalid option", arg);
7446 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007447}
7448
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007449static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007450{
7451 int n = 1;
7452 if (argv[1]) {
7453 n = atoi(argv[1]);
7454 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007455 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007456 if (G.global_args_malloced) {
7457 int m = 1;
7458 while (m <= n)
7459 free(G.global_argv[m++]);
7460 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007461 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007462 memmove(&G.global_argv[1], &G.global_argv[n+1],
7463 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007464 return EXIT_SUCCESS;
7465 }
7466 return EXIT_FAILURE;
7467}
7468
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007469static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007470{
Mike Frysinger93cadc22009-05-27 17:06:25 -04007471 char *arg_path;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007472 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007473 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007474#if ENABLE_HUSH_FUNCTIONS
7475 smallint sv_flg;
7476#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007477
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007478 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007479 return EXIT_FAILURE;
7480
Mike Frysinger93cadc22009-05-27 17:06:25 -04007481 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7482 input = fopen_for_read(arg_path);
7483 free(arg_path);
7484 } else
7485 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007486 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007487 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007488 return EXIT_FAILURE;
7489 }
7490 close_on_exec_on(fileno(input));
7491
Mike Frysinger885b6f22009-04-18 21:04:25 +00007492#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007493 sv_flg = G.flag_return_in_progress;
7494 /* "we are inside sourced file, ok to use return" */
7495 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007496#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007497 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007498
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007499 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007500 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007501
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007502 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00007503#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007504 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007505#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007506
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007507 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007508}
7509
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007510static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007511{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007512 int rc;
7513 mode_t mask;
7514
7515 mask = umask(0);
7516 if (argv[1]) {
7517 mode_t old_mask = mask;
7518
7519 mask ^= 0777;
7520 rc = bb_parse_mode(argv[1], &mask);
7521 mask ^= 0777;
7522 if (rc == 0) {
7523 mask = old_mask;
7524 /* bash messages:
7525 * bash: umask: 'q': invalid symbolic mode operator
7526 * bash: umask: 999: octal number out of range
7527 */
7528 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007529 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007530 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007531 rc = 1;
7532 /* Mimic bash */
7533 printf("%04o\n", (unsigned) mask);
7534 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007535 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007536 umask(mask);
7537
7538 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007539}
7540
Mike Frysingerd690f682009-03-30 06:50:54 +00007541/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007542static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007543{
Mike Frysingerd690f682009-03-30 06:50:54 +00007544 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00007545 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00007546
Denis Vlasenko28e67962009-04-26 23:22:40 +00007547 /* "!": do not abort on errors */
7548 /* "+": stop at 1st non-option */
7549 opts = getopt32(argv, "!+vf");
7550 if (opts == (unsigned)-1)
7551 return EXIT_FAILURE;
7552 if (opts == 3) {
7553 bb_error_msg("unset: -v and -f are exclusive");
7554 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00007555 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00007556 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00007557
7558 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007559 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00007560 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007561 if (unset_local_var(*argv)) {
7562 /* unset <nonexistent_var> doesn't fail.
7563 * Error is when one tries to unset RO var.
7564 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00007565 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007566 }
Mike Frysingerd690f682009-03-30 06:50:54 +00007567 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00007568#if ENABLE_HUSH_FUNCTIONS
7569 else {
7570 unset_func(*argv);
7571 }
7572#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007573 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00007574 }
7575 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007576}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007577
Mike Frysinger56bdea12009-03-28 20:01:58 +00007578/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007579static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00007580{
7581 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007582 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007583
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007584 if (*++argv == NULL) {
7585 /* Don't care about wait results */
7586 /* Note 1: must wait until there are no more children */
7587 /* Note 2: must be interruptible */
7588 /* Examples:
7589 * $ sleep 3 & sleep 6 & wait
7590 * [1] 30934 sleep 3
7591 * [2] 30935 sleep 6
7592 * [1] Done sleep 3
7593 * [2] Done sleep 6
7594 * $ sleep 3 & sleep 6 & wait
7595 * [1] 30936 sleep 3
7596 * [2] 30937 sleep 6
7597 * [1] Done sleep 3
7598 * ^C <-- after ~4 sec from keyboard
7599 * $
7600 */
7601 sigaddset(&G.blocked_set, SIGCHLD);
7602 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7603 while (1) {
7604 checkjobs(NULL);
7605 if (errno == ECHILD)
7606 break;
7607 /* Wait for SIGCHLD or any other signal of interest */
7608 /* sigtimedwait with infinite timeout: */
7609 sig = sigwaitinfo(&G.blocked_set, NULL);
7610 if (sig > 0) {
7611 sig = check_and_run_traps(sig);
7612 if (sig && sig != SIGCHLD) { /* see note 2 */
7613 ret = 128 + sig;
7614 break;
7615 }
7616 }
7617 }
7618 sigdelset(&G.blocked_set, SIGCHLD);
7619 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7620 return ret;
7621 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00007622
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007623 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00007624 while (*argv) {
7625 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00007626 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007627 /* mimic bash message */
7628 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007629 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007630 }
7631 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00007632 if (WIFSIGNALED(status))
7633 ret = 128 + WTERMSIG(status);
7634 else if (WIFEXITED(status))
7635 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00007636 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00007637 ret = EXIT_FAILURE;
7638 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007639 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007640 ret = 127;
7641 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00007642 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007643 }
7644
7645 return ret;
7646}
7647
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007648#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7649static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7650{
7651 if (argv[1]) {
7652 def = bb_strtou(argv[1], NULL, 10);
7653 if (errno || def < def_min || argv[2]) {
7654 bb_error_msg("%s: bad arguments", argv[0]);
7655 def = UINT_MAX;
7656 }
7657 }
7658 return def;
7659}
7660#endif
7661
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007662#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007663static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007664{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007665 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007666 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007667 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00007668 return EXIT_SUCCESS; /* bash compat */
7669 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007670 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007671
7672 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7673 if (depth == UINT_MAX)
7674 G.flag_break_continue = BC_BREAK;
7675 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00007676 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007677
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007678 return EXIT_SUCCESS;
7679}
7680
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007681static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007682{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007683 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7684 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007685}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007686#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007687
7688#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007689static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007690{
7691 int rc;
7692
7693 if (G.flag_return_in_progress != -1) {
7694 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7695 return EXIT_FAILURE; /* bash compat */
7696 }
7697
7698 G.flag_return_in_progress = 1;
7699
7700 /* bash:
7701 * out of range: wraps around at 256, does not error out
7702 * non-numeric param:
7703 * f() { false; return qwe; }; f; echo $?
7704 * bash: return: qwe: numeric argument required <== we do this
7705 * 255 <== we also do this
7706 */
7707 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
7708 return rc;
7709}
7710#endif